]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/item.rs
Rename `rust_2015` => `is_rust_2015`
[rust.git] / compiler / rustc_parse / src / parser / item.rs
1 use crate::errors::{
2     AmbiguousMissingKwForItemSub, AssociatedStaticItemNotAllowed, AsyncFnIn2015,
3     BoundsNotAllowedOnTraitAliases, ConstGlobalCannotBeMutable, ConstLetMutuallyExclusive,
4     DefaultNotFollowedByItem, DocCommentDoesNotDocumentAnything, EnumStructMutuallyExclusive,
5     ExpectedTraitInTraitImplFoundType, ExternCrateNameWithDashes, ExternCrateNameWithDashesSugg,
6     ExternItemCannotBeConst, HelpUseLatestEdition, MissingConstType, MissingForInTraitImpl,
7     MissingKeywordForItemDefinition, MissingTraitInTraitImpl, SelfArgumentPointer,
8     TraitAliasCannotBeAuto, TraitAliasCannotBeUnsafe, UnexpectedTokenAfterStructName,
9     UseEmptyBlockNotSemi, VisibilityNotFollowedByItem,
10 };
11
12 use super::diagnostics::{dummy_arg, ConsumeClosingDelim};
13 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
14 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
15 use crate::errors::FnTypoWithImpl;
16 use rustc_ast::ast::*;
17 use rustc_ast::ptr::P;
18 use rustc_ast::token::{self, Delimiter, TokenKind};
19 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
20 use rustc_ast::util::case::Case;
21 use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
22 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
23 use rustc_ast::{BindingAnnotation, Block, FnDecl, FnSig, Param, SelfKind};
24 use rustc_ast::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData};
25 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
26 use rustc_ast::{MacCall, MacDelimiter};
27 use rustc_ast_pretty::pprust;
28 use rustc_errors::{
29     struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, PResult,
30     StashKey,
31 };
32 use rustc_span::edition::Edition;
33 use rustc_span::lev_distance::lev_distance;
34 use rustc_span::source_map::{self, Span};
35 use rustc_span::symbol::{kw, sym, Ident, Symbol};
36 use rustc_span::DUMMY_SP;
37 use std::fmt::Write;
38 use std::mem;
39 use thin_vec::ThinVec;
40
41 impl<'a> Parser<'a> {
42     /// Parses a source module as a crate. This is the main entry point for the parser.
43     pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
44         let (attrs, items, spans) = self.parse_mod(&token::Eof)?;
45         Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
46     }
47
48     /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
49     fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemInfo> {
50         let unsafety = self.parse_unsafety(Case::Sensitive);
51         self.expect_keyword(kw::Mod)?;
52         let id = self.parse_ident()?;
53         let mod_kind = if self.eat(&token::Semi) {
54             ModKind::Unloaded
55         } else {
56             self.expect(&token::OpenDelim(Delimiter::Brace))?;
57             let (inner_attrs, items, inner_span) =
58                 self.parse_mod(&token::CloseDelim(Delimiter::Brace))?;
59             attrs.extend(inner_attrs);
60             ModKind::Loaded(items, Inline::Yes, inner_span)
61         };
62         Ok((id, ItemKind::Mod(unsafety, mod_kind)))
63     }
64
65     /// Parses the contents of a module (inner attributes followed by module items).
66     pub fn parse_mod(
67         &mut self,
68         term: &TokenKind,
69     ) -> PResult<'a, (AttrVec, Vec<P<Item>>, ModSpans)> {
70         let lo = self.token.span;
71         let attrs = self.parse_inner_attributes()?;
72
73         let post_attr_lo = self.token.span;
74         let mut items = vec![];
75         while let Some(item) = self.parse_item(ForceCollect::No)? {
76             items.push(item);
77             self.maybe_consume_incorrect_semicolon(&items);
78         }
79
80         if !self.eat(term) {
81             let token_str = super::token_descr(&self.token);
82             if !self.maybe_consume_incorrect_semicolon(&items) {
83                 let msg = &format!("expected item, found {token_str}");
84                 let mut err = self.struct_span_err(self.token.span, msg);
85                 let label = if self.is_kw_followed_by_ident(kw::Let) {
86                     "consider using `const` or `static` instead of `let` for global variables"
87                 } else {
88                     "expected item"
89                 };
90                 err.span_label(self.token.span, label);
91                 return Err(err);
92             }
93         }
94
95         let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
96         let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
97         Ok((attrs, items, mod_spans))
98     }
99 }
100
101 pub(super) type ItemInfo = (Ident, ItemKind);
102
103 impl<'a> Parser<'a> {
104     pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
105         let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
106         self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
107     }
108
109     fn parse_item_(
110         &mut self,
111         fn_parse_mode: FnParseMode,
112         force_collect: ForceCollect,
113     ) -> PResult<'a, Option<Item>> {
114         self.recover_diff_marker();
115         let attrs = self.parse_outer_attributes()?;
116         self.recover_diff_marker();
117         self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
118     }
119
120     pub(super) fn parse_item_common(
121         &mut self,
122         attrs: AttrWrapper,
123         mac_allowed: bool,
124         attrs_allowed: bool,
125         fn_parse_mode: FnParseMode,
126         force_collect: ForceCollect,
127     ) -> PResult<'a, Option<Item>> {
128         // Don't use `maybe_whole` so that we have precise control
129         // over when we bump the parser
130         if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
131             let mut item = item.clone();
132             self.bump();
133
134             attrs.prepend_to_nt_inner(&mut item.attrs);
135             return Ok(Some(item.into_inner()));
136         };
137
138         let mut unclosed_delims = vec![];
139         let item =
140             self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
141                 let item =
142                     this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
143                 unclosed_delims.append(&mut this.unclosed_delims);
144                 Ok((item?, TrailingToken::None))
145             })?;
146
147         self.unclosed_delims.append(&mut unclosed_delims);
148         Ok(item)
149     }
150
151     fn parse_item_common_(
152         &mut self,
153         mut attrs: AttrVec,
154         mac_allowed: bool,
155         attrs_allowed: bool,
156         fn_parse_mode: FnParseMode,
157     ) -> PResult<'a, Option<Item>> {
158         let lo = self.token.span;
159         let vis = self.parse_visibility(FollowedByType::No)?;
160         let mut def = self.parse_defaultness();
161         let kind = self.parse_item_kind(
162             &mut attrs,
163             mac_allowed,
164             lo,
165             &vis,
166             &mut def,
167             fn_parse_mode,
168             Case::Sensitive,
169         )?;
170         if let Some((ident, kind)) = kind {
171             self.error_on_unconsumed_default(def, &kind);
172             let span = lo.to(self.prev_token.span);
173             let id = DUMMY_NODE_ID;
174             let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
175             return Ok(Some(item));
176         }
177
178         // At this point, we have failed to parse an item.
179         if !matches!(vis.kind, VisibilityKind::Inherited) {
180             self.sess.emit_err(VisibilityNotFollowedByItem { span: vis.span, vis });
181         }
182
183         if let Defaultness::Default(span) = def {
184             self.sess.emit_err(DefaultNotFollowedByItem { span });
185         }
186
187         if !attrs_allowed {
188             self.recover_attrs_no_item(&attrs)?;
189         }
190         Ok(None)
191     }
192
193     /// Error in-case `default` was parsed in an in-appropriate context.
194     fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
195         if let Defaultness::Default(span) = def {
196             let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
197             self.struct_span_err(span, &msg)
198                 .span_label(span, "`default` because of this")
199                 .note("only associated `fn`, `const`, and `type` items can be `default`")
200                 .emit();
201         }
202     }
203
204     /// Parses one of the items allowed by the flags.
205     fn parse_item_kind(
206         &mut self,
207         attrs: &mut AttrVec,
208         macros_allowed: bool,
209         lo: Span,
210         vis: &Visibility,
211         def: &mut Defaultness,
212         fn_parse_mode: FnParseMode,
213         case: Case,
214     ) -> PResult<'a, Option<ItemInfo>> {
215         let def_final = def == &Defaultness::Final;
216         let mut def_ = || mem::replace(def, Defaultness::Final);
217
218         let info = if self.eat_keyword_case(kw::Use, case) {
219             self.parse_use_item()?
220         } else if self.check_fn_front_matter(def_final, case) {
221             // FUNCTION ITEM
222             let (ident, sig, generics, body) =
223                 self.parse_fn(attrs, fn_parse_mode, lo, vis, case)?;
224             (ident, ItemKind::Fn(Box::new(Fn { defaultness: def_(), sig, generics, body })))
225         } else if self.eat_keyword(kw::Extern) {
226             if self.eat_keyword(kw::Crate) {
227                 // EXTERN CRATE
228                 self.parse_item_extern_crate()?
229             } else {
230                 // EXTERN BLOCK
231                 self.parse_item_foreign_mod(attrs, Unsafe::No)?
232             }
233         } else if self.is_unsafe_foreign_mod() {
234             // EXTERN BLOCK
235             let unsafety = self.parse_unsafety(Case::Sensitive);
236             self.expect_keyword(kw::Extern)?;
237             self.parse_item_foreign_mod(attrs, unsafety)?
238         } else if self.is_static_global() {
239             // STATIC ITEM
240             self.bump(); // `static`
241             let m = self.parse_mutability();
242             let (ident, ty, expr) = self.parse_item_global(Some(m))?;
243             (ident, ItemKind::Static(ty, m, expr))
244         } else if let Const::Yes(const_span) = self.parse_constness(Case::Sensitive) {
245             // CONST ITEM
246             if self.token.is_keyword(kw::Impl) {
247                 // recover from `const impl`, suggest `impl const`
248                 self.recover_const_impl(const_span, attrs, def_())?
249             } else {
250                 self.recover_const_mut(const_span);
251                 let (ident, ty, expr) = self.parse_item_global(None)?;
252                 (ident, ItemKind::Const(def_(), ty, expr))
253             }
254         } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
255             // TRAIT ITEM
256             self.parse_item_trait(attrs, lo)?
257         } else if self.check_keyword(kw::Impl)
258             || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
259         {
260             // IMPL ITEM
261             self.parse_item_impl(attrs, def_())?
262         } else if self.check_keyword(kw::Mod)
263             || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
264         {
265             // MODULE ITEM
266             self.parse_item_mod(attrs)?
267         } else if self.eat_keyword(kw::Type) {
268             // TYPE ITEM
269             self.parse_type_alias(def_())?
270         } else if self.eat_keyword(kw::Enum) {
271             // ENUM ITEM
272             self.parse_item_enum()?
273         } else if self.eat_keyword(kw::Struct) {
274             // STRUCT ITEM
275             self.parse_item_struct()?
276         } else if self.is_kw_followed_by_ident(kw::Union) {
277             // UNION ITEM
278             self.bump(); // `union`
279             self.parse_item_union()?
280         } else if self.eat_keyword(kw::Macro) {
281             // MACROS 2.0 ITEM
282             self.parse_item_decl_macro(lo)?
283         } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
284             // MACRO_RULES ITEM
285             self.parse_item_macro_rules(vis, has_bang)?
286         } else if self.isnt_macro_invocation()
287             && (self.token.is_ident_named(sym::import)
288                 || self.token.is_ident_named(sym::using)
289                 || self.token.is_ident_named(sym::include)
290                 || self.token.is_ident_named(sym::require))
291         {
292             return self.recover_import_as_use();
293         } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
294             self.recover_missing_kw_before_item()?;
295             return Ok(None);
296         } else if self.isnt_macro_invocation() && case == Case::Sensitive {
297             _ = def_;
298
299             // Recover wrong cased keywords
300             return self.parse_item_kind(
301                 attrs,
302                 macros_allowed,
303                 lo,
304                 vis,
305                 def,
306                 fn_parse_mode,
307                 Case::Insensitive,
308             );
309         } else if macros_allowed && self.check_path() {
310             // MACRO INVOCATION ITEM
311             (Ident::empty(), ItemKind::MacCall(P(self.parse_item_macro(vis)?)))
312         } else {
313             return Ok(None);
314         };
315         Ok(Some(info))
316     }
317
318     fn recover_import_as_use(&mut self) -> PResult<'a, Option<(Ident, ItemKind)>> {
319         let span = self.token.span;
320         let token_name = super::token_descr(&self.token);
321         let snapshot = self.create_snapshot_for_diagnostic();
322         self.bump();
323         match self.parse_use_item() {
324             Ok(u) => {
325                 self.struct_span_err(span, format!("expected item, found {token_name}"))
326                     .span_suggestion_short(
327                         span,
328                         "items are imported using the `use` keyword",
329                         "use",
330                         Applicability::MachineApplicable,
331                     )
332                     .emit();
333                 Ok(Some(u))
334             }
335             Err(e) => {
336                 e.cancel();
337                 self.restore_snapshot(snapshot);
338                 Ok(None)
339             }
340         }
341     }
342
343     fn parse_use_item(&mut self) -> PResult<'a, (Ident, ItemKind)> {
344         let tree = self.parse_use_tree()?;
345         if let Err(mut e) = self.expect_semi() {
346             match tree.kind {
347                 UseTreeKind::Glob => {
348                     e.note("the wildcard token must be last on the path");
349                 }
350                 UseTreeKind::Nested(..) => {
351                     e.note("glob-like brace syntax must be last on the path");
352                 }
353                 _ => (),
354             }
355             return Err(e);
356         }
357         Ok((Ident::empty(), ItemKind::Use(tree)))
358     }
359
360     /// When parsing a statement, would the start of a path be an item?
361     pub(super) fn is_path_start_item(&mut self) -> bool {
362         self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
363         || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
364         || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
365         || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
366     }
367
368     /// Are we sure this could not possibly be a macro invocation?
369     fn isnt_macro_invocation(&mut self) -> bool {
370         self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
371     }
372
373     /// Recover on encountering a struct or method definition where the user
374     /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
375     fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
376         // Space between `pub` keyword and the identifier
377         //
378         //     pub   S {}
379         //        ^^^ `sp` points here
380         let sp = self.prev_token.span.between(self.token.span);
381         let full_sp = self.prev_token.span.to(self.token.span);
382         let ident_sp = self.token.span;
383
384         let ident = if self.look_ahead(1, |t| {
385             [
386                 token::Lt,
387                 token::OpenDelim(Delimiter::Brace),
388                 token::OpenDelim(Delimiter::Parenthesis),
389             ]
390             .contains(&t.kind)
391         }) {
392             self.parse_ident().unwrap()
393         } else {
394             return Ok(());
395         };
396
397         let mut found_generics = false;
398         if self.check(&token::Lt) {
399             found_generics = true;
400             self.eat_to_tokens(&[&token::Gt]);
401             self.bump(); // `>`
402         }
403
404         let err = if self.check(&token::OpenDelim(Delimiter::Brace)) {
405             // possible public struct definition where `struct` was forgotten
406             Some(MissingKeywordForItemDefinition::Struct { span: sp, ident })
407         } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
408             // possible public function or tuple struct definition where `fn`/`struct` was
409             // forgotten
410             self.bump(); // `(`
411             let is_method = self.recover_self_param();
412
413             self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::Yes);
414
415             let err = if self.check(&token::RArrow)
416                 || self.check(&token::OpenDelim(Delimiter::Brace))
417             {
418                 self.eat_to_tokens(&[&token::OpenDelim(Delimiter::Brace)]);
419                 self.bump(); // `{`
420                 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
421                 if is_method {
422                     MissingKeywordForItemDefinition::Method { span: sp, ident }
423                 } else {
424                     MissingKeywordForItemDefinition::Function { span: sp, ident }
425                 }
426             } else if self.check(&token::Semi) {
427                 MissingKeywordForItemDefinition::Struct { span: sp, ident }
428             } else {
429                 MissingKeywordForItemDefinition::Ambiguous {
430                     span: sp,
431                     subdiag: if found_generics {
432                         None
433                     } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
434                         Some(AmbiguousMissingKwForItemSub::SuggestMacro { span: full_sp, snippet })
435                     } else {
436                         Some(AmbiguousMissingKwForItemSub::HelpMacro)
437                     },
438                 }
439             };
440             Some(err)
441         } else if found_generics {
442             Some(MissingKeywordForItemDefinition::Ambiguous { span: sp, subdiag: None })
443         } else {
444             None
445         };
446
447         if let Some(err) = err {
448             Err(err.into_diagnostic(&self.sess.span_diagnostic))
449         } else {
450             Ok(())
451         }
452     }
453
454     /// Parses an item macro, e.g., `item!();`.
455     fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
456         let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
457         self.expect(&token::Not)?; // `!`
458         match self.parse_delim_args() {
459             // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
460             Ok(args) => {
461                 self.eat_semi_for_macro_if_needed(&args);
462                 self.complain_if_pub_macro(vis, false);
463                 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
464             }
465
466             Err(mut err) => {
467                 // Maybe the user misspelled `macro_rules` (issue #91227)
468                 if self.token.is_ident()
469                     && path.segments.len() == 1
470                     && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
471                 {
472                     err.span_suggestion(
473                         path.span,
474                         "perhaps you meant to define a macro",
475                         "macro_rules",
476                         Applicability::MachineApplicable,
477                     );
478                 }
479                 Err(err)
480             }
481         }
482     }
483
484     /// Recover if we parsed attributes and expected an item but there was none.
485     fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
486         let ([start @ end] | [start, .., end]) = attrs else {
487             return Ok(());
488         };
489         let msg = if end.is_doc_comment() {
490             "expected item after doc comment"
491         } else {
492             "expected item after attributes"
493         };
494         let mut err = self.struct_span_err(end.span, msg);
495         if end.is_doc_comment() {
496             err.span_label(end.span, "this doc comment doesn't document anything");
497         } else if self.token.kind == TokenKind::Semi {
498             err.span_suggestion_verbose(
499                 self.token.span,
500                 "consider removing this semicolon",
501                 "",
502                 Applicability::MaybeIncorrect,
503             );
504         }
505         if let [.., penultimate, _] = attrs {
506             err.span_label(start.span.to(penultimate.span), "other attributes here");
507         }
508         Err(err)
509     }
510
511     fn is_async_fn(&self) -> bool {
512         self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
513     }
514
515     fn parse_polarity(&mut self) -> ast::ImplPolarity {
516         // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
517         if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
518             self.bump(); // `!`
519             ast::ImplPolarity::Negative(self.prev_token.span)
520         } else {
521             ast::ImplPolarity::Positive
522         }
523     }
524
525     /// Parses an implementation item.
526     ///
527     /// ```ignore (illustrative)
528     /// impl<'a, T> TYPE { /* impl items */ }
529     /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
530     /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
531     /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
532     /// ```
533     ///
534     /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
535     /// ```ebnf
536     /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
537     /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
538     /// ```
539     fn parse_item_impl(
540         &mut self,
541         attrs: &mut AttrVec,
542         defaultness: Defaultness,
543     ) -> PResult<'a, ItemInfo> {
544         let unsafety = self.parse_unsafety(Case::Sensitive);
545         self.expect_keyword(kw::Impl)?;
546
547         // First, parse generic parameters if necessary.
548         let mut generics = if self.choose_generics_over_qpath(0) {
549             self.parse_generics()?
550         } else {
551             let mut generics = Generics::default();
552             // impl A for B {}
553             //    /\ this is where `generics.span` should point when there are no type params.
554             generics.span = self.prev_token.span.shrink_to_hi();
555             generics
556         };
557
558         let constness = self.parse_constness(Case::Sensitive);
559         if let Const::Yes(span) = constness {
560             self.sess.gated_spans.gate(sym::const_trait_impl, span);
561         }
562
563         let polarity = self.parse_polarity();
564
565         // Parse both types and traits as a type, then reinterpret if necessary.
566         let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
567         let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
568         {
569             let span = self.prev_token.span.between(self.token.span);
570             self.sess
571                 .emit_err(MissingTraitInTraitImpl { span, for_span: span.to(self.token.span) });
572
573             P(Ty {
574                 kind: TyKind::Path(None, err_path(span)),
575                 span,
576                 id: DUMMY_NODE_ID,
577                 tokens: None,
578             })
579         } else {
580             self.parse_ty_with_generics_recovery(&generics)?
581         };
582
583         // If `for` is missing we try to recover.
584         let has_for = self.eat_keyword(kw::For);
585         let missing_for_span = self.prev_token.span.between(self.token.span);
586
587         let ty_second = if self.token == token::DotDot {
588             // We need to report this error after `cfg` expansion for compatibility reasons
589             self.bump(); // `..`, do not add it to expected tokens
590             Some(self.mk_ty(self.prev_token.span, TyKind::Err))
591         } else if has_for || self.token.can_begin_type() {
592             Some(self.parse_ty()?)
593         } else {
594             None
595         };
596
597         generics.where_clause = self.parse_where_clause()?;
598
599         let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
600
601         let item_kind = match ty_second {
602             Some(ty_second) => {
603                 // impl Trait for Type
604                 if !has_for {
605                     self.sess.emit_err(MissingForInTraitImpl { span: missing_for_span });
606                 }
607
608                 let ty_first = ty_first.into_inner();
609                 let path = match ty_first.kind {
610                     // This notably includes paths passed through `ty` macro fragments (#46438).
611                     TyKind::Path(None, path) => path,
612                     _ => {
613                         self.sess
614                             .emit_err(ExpectedTraitInTraitImplFoundType { span: ty_first.span });
615                         err_path(ty_first.span)
616                     }
617                 };
618                 let trait_ref = TraitRef { path, ref_id: ty_first.id };
619
620                 ItemKind::Impl(Box::new(Impl {
621                     unsafety,
622                     polarity,
623                     defaultness,
624                     constness,
625                     generics,
626                     of_trait: Some(trait_ref),
627                     self_ty: ty_second,
628                     items: impl_items,
629                 }))
630             }
631             None => {
632                 // impl Type
633                 ItemKind::Impl(Box::new(Impl {
634                     unsafety,
635                     polarity,
636                     defaultness,
637                     constness,
638                     generics,
639                     of_trait: None,
640                     self_ty: ty_first,
641                     items: impl_items,
642                 }))
643             }
644         };
645
646         Ok((Ident::empty(), item_kind))
647     }
648
649     fn parse_item_list<T>(
650         &mut self,
651         attrs: &mut AttrVec,
652         mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
653     ) -> PResult<'a, Vec<T>> {
654         let open_brace_span = self.token.span;
655
656         // Recover `impl Ty;` instead of `impl Ty {}`
657         if self.token == TokenKind::Semi {
658             self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
659             self.bump();
660             return Ok(vec![]);
661         }
662
663         self.expect(&token::OpenDelim(Delimiter::Brace))?;
664         attrs.extend(self.parse_inner_attributes()?);
665
666         let mut items = Vec::new();
667         while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
668             if self.recover_doc_comment_before_brace() {
669                 continue;
670             }
671             self.recover_diff_marker();
672             match parse_item(self) {
673                 Ok(None) => {
674                     let mut is_unnecessary_semicolon = !items.is_empty()
675                         // When the close delim is `)` in a case like the following, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
676                         // but the actual `token.kind` is `token::CloseDelim(Delimiter::Brace)`.
677                         // This is because the `token.kind` of the close delim is treated as the same as
678                         // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
679                         // Therefore, `token.kind` should not be compared here.
680                         //
681                         // issue-60075.rs
682                         // ```
683                         // trait T {
684                         //     fn qux() -> Option<usize> {
685                         //         let _ = if true {
686                         //         });
687                         //          ^ this close delim
688                         //         Some(4)
689                         //     }
690                         // ```
691                         && self
692                             .span_to_snippet(self.prev_token.span)
693                             .map_or(false, |snippet| snippet == "}")
694                         && self.token.kind == token::Semi;
695                     let mut semicolon_span = self.token.span;
696                     if !is_unnecessary_semicolon {
697                         // #105369, Detect spurious `;` before assoc fn body
698                         is_unnecessary_semicolon = self.token == token::OpenDelim(Delimiter::Brace)
699                             && self.prev_token.kind == token::Semi;
700                         semicolon_span = self.prev_token.span;
701                     }
702                     // We have to bail or we'll potentially never make progress.
703                     let non_item_span = self.token.span;
704                     let is_let = self.token.is_keyword(kw::Let);
705
706                     let mut err = self.struct_span_err(non_item_span, "non-item in item list");
707                     self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
708                     if is_let {
709                         err.span_suggestion(
710                             non_item_span,
711                             "consider using `const` instead of `let` for associated const",
712                             "const",
713                             Applicability::MachineApplicable,
714                         );
715                     } else {
716                         err.span_label(open_brace_span, "item list starts here")
717                             .span_label(non_item_span, "non-item starts here")
718                             .span_label(self.prev_token.span, "item list ends here");
719                     }
720                     if is_unnecessary_semicolon {
721                         err.span_suggestion(
722                             semicolon_span,
723                             "consider removing this semicolon",
724                             "",
725                             Applicability::MaybeIncorrect,
726                         );
727                     }
728                     err.emit();
729                     break;
730                 }
731                 Ok(Some(item)) => items.extend(item),
732                 Err(mut err) => {
733                     self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
734                     err.span_label(open_brace_span, "while parsing this item list starting here")
735                         .span_label(self.prev_token.span, "the item list ends here")
736                         .emit();
737                     break;
738                 }
739             }
740         }
741         Ok(items)
742     }
743
744     /// Recover on a doc comment before `}`.
745     fn recover_doc_comment_before_brace(&mut self) -> bool {
746         if let token::DocComment(..) = self.token.kind {
747             if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
748                 // FIXME: merge with `DocCommentDoesNotDocumentAnything` (E0585)
749                 struct_span_err!(
750                     self.diagnostic(),
751                     self.token.span,
752                     E0584,
753                     "found a documentation comment that doesn't document anything",
754                 )
755                 .span_label(self.token.span, "this doc comment doesn't document anything")
756                 .help(
757                     "doc comments must come before what they document, if a comment was \
758                     intended use `//`",
759                 )
760                 .emit();
761                 self.bump();
762                 return true;
763             }
764         }
765         false
766     }
767
768     /// Parses defaultness (i.e., `default` or nothing).
769     fn parse_defaultness(&mut self) -> Defaultness {
770         // We are interested in `default` followed by another identifier.
771         // However, we must avoid keywords that occur as binary operators.
772         // Currently, the only applicable keyword is `as` (`default as Ty`).
773         if self.check_keyword(kw::Default)
774             && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
775         {
776             self.bump(); // `default`
777             Defaultness::Default(self.prev_token.uninterpolated_span())
778         } else {
779             Defaultness::Final
780         }
781     }
782
783     /// Is this an `(unsafe auto? | auto) trait` item?
784     fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
785         // auto trait
786         self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
787             // unsafe auto trait
788             || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
789     }
790
791     /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
792     fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
793         let unsafety = self.parse_unsafety(Case::Sensitive);
794         // Parse optional `auto` prefix.
795         let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
796
797         self.expect_keyword(kw::Trait)?;
798         let ident = self.parse_ident()?;
799         let mut generics = self.parse_generics()?;
800
801         // Parse optional colon and supertrait bounds.
802         let had_colon = self.eat(&token::Colon);
803         let span_at_colon = self.prev_token.span;
804         let bounds = if had_colon {
805             self.parse_generic_bounds(Some(self.prev_token.span))?
806         } else {
807             Vec::new()
808         };
809
810         let span_before_eq = self.prev_token.span;
811         if self.eat(&token::Eq) {
812             // It's a trait alias.
813             if had_colon {
814                 let span = span_at_colon.to(span_before_eq);
815                 self.sess.emit_err(BoundsNotAllowedOnTraitAliases { span });
816             }
817
818             let bounds = self.parse_generic_bounds(None)?;
819             generics.where_clause = self.parse_where_clause()?;
820             self.expect_semi()?;
821
822             let whole_span = lo.to(self.prev_token.span);
823             if is_auto == IsAuto::Yes {
824                 self.sess.emit_err(TraitAliasCannotBeAuto { span: whole_span });
825             }
826             if let Unsafe::Yes(_) = unsafety {
827                 self.sess.emit_err(TraitAliasCannotBeUnsafe { span: whole_span });
828             }
829
830             self.sess.gated_spans.gate(sym::trait_alias, whole_span);
831
832             Ok((ident, ItemKind::TraitAlias(generics, bounds)))
833         } else {
834             // It's a normal trait.
835             generics.where_clause = self.parse_where_clause()?;
836             let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
837             Ok((
838                 ident,
839                 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
840             ))
841         }
842     }
843
844     pub fn parse_impl_item(
845         &mut self,
846         force_collect: ForceCollect,
847     ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
848         let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
849         self.parse_assoc_item(fn_parse_mode, force_collect)
850     }
851
852     pub fn parse_trait_item(
853         &mut self,
854         force_collect: ForceCollect,
855     ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
856         let fn_parse_mode =
857             FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
858         self.parse_assoc_item(fn_parse_mode, force_collect)
859     }
860
861     /// Parses associated items.
862     fn parse_assoc_item(
863         &mut self,
864         fn_parse_mode: FnParseMode,
865         force_collect: ForceCollect,
866     ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
867         Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
868             |Item { attrs, id, span, vis, ident, kind, tokens }| {
869                 let kind = match AssocItemKind::try_from(kind) {
870                     Ok(kind) => kind,
871                     Err(kind) => match kind {
872                         ItemKind::Static(a, _, b) => {
873                             self.sess.emit_err(AssociatedStaticItemNotAllowed { span });
874                             AssocItemKind::Const(Defaultness::Final, a, b)
875                         }
876                         _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
877                     },
878                 };
879                 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
880             },
881         ))
882     }
883
884     /// Parses a `type` alias with the following grammar:
885     /// ```ebnf
886     /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
887     /// ```
888     /// The `"type"` has already been eaten.
889     fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
890         let ident = self.parse_ident()?;
891         let mut generics = self.parse_generics()?;
892
893         // Parse optional colon and param bounds.
894         let bounds =
895             if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
896         let before_where_clause = self.parse_where_clause()?;
897
898         let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
899
900         let after_where_clause = self.parse_where_clause()?;
901
902         let where_clauses = (
903             TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
904             TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
905         );
906         let where_predicates_split = before_where_clause.predicates.len();
907         let mut predicates = before_where_clause.predicates;
908         predicates.extend(after_where_clause.predicates.into_iter());
909         let where_clause = WhereClause {
910             has_where_token: before_where_clause.has_where_token
911                 || after_where_clause.has_where_token,
912             predicates,
913             span: DUMMY_SP,
914         };
915         generics.where_clause = where_clause;
916
917         self.expect_semi()?;
918
919         Ok((
920             ident,
921             ItemKind::TyAlias(Box::new(TyAlias {
922                 defaultness,
923                 generics,
924                 where_clauses,
925                 where_predicates_split,
926                 bounds,
927                 ty,
928             })),
929         ))
930     }
931
932     /// Parses a `UseTree`.
933     ///
934     /// ```text
935     /// USE_TREE = [`::`] `*` |
936     ///            [`::`] `{` USE_TREE_LIST `}` |
937     ///            PATH `::` `*` |
938     ///            PATH `::` `{` USE_TREE_LIST `}` |
939     ///            PATH [`as` IDENT]
940     /// ```
941     fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
942         let lo = self.token.span;
943
944         let mut prefix =
945             ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo(), tokens: None };
946         let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
947             || self.check(&token::BinOp(token::Star))
948             || self.is_import_coupler()
949         {
950             // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
951             let mod_sep_ctxt = self.token.span.ctxt();
952             if self.eat(&token::ModSep) {
953                 prefix
954                     .segments
955                     .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
956             }
957
958             self.parse_use_tree_glob_or_nested()?
959         } else {
960             // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
961             prefix = self.parse_path(PathStyle::Mod)?;
962
963             if self.eat(&token::ModSep) {
964                 self.parse_use_tree_glob_or_nested()?
965             } else {
966                 // Recover from using a colon as path separator.
967                 while self.eat_noexpect(&token::Colon) {
968                     self.struct_span_err(self.prev_token.span, "expected `::`, found `:`")
969                         .span_suggestion_short(
970                             self.prev_token.span,
971                             "use double colon",
972                             "::",
973                             Applicability::MachineApplicable,
974                         )
975                         .note_once("import paths are delimited using `::`")
976                         .emit();
977
978                     // We parse the rest of the path and append it to the original prefix.
979                     self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
980                     prefix.span = lo.to(self.prev_token.span);
981                 }
982
983                 UseTreeKind::Simple(self.parse_rename()?)
984             }
985         };
986
987         Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
988     }
989
990     /// Parses `*` or `{...}`.
991     fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
992         Ok(if self.eat(&token::BinOp(token::Star)) {
993             UseTreeKind::Glob
994         } else {
995             UseTreeKind::Nested(self.parse_use_tree_list()?)
996         })
997     }
998
999     /// Parses a `UseTreeKind::Nested(list)`.
1000     ///
1001     /// ```text
1002     /// USE_TREE_LIST = Ã˜ | (USE_TREE `,`)* USE_TREE [`,`]
1003     /// ```
1004     fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1005         self.parse_delim_comma_seq(Delimiter::Brace, |p| {
1006             p.recover_diff_marker();
1007             Ok((p.parse_use_tree()?, DUMMY_NODE_ID))
1008         })
1009         .map(|(r, _)| r)
1010     }
1011
1012     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1013         if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1014     }
1015
1016     fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1017         match self.token.ident() {
1018             Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1019                 self.bump();
1020                 Ok(ident)
1021             }
1022             _ => self.parse_ident(),
1023         }
1024     }
1025
1026     /// Parses `extern crate` links.
1027     ///
1028     /// # Examples
1029     ///
1030     /// ```ignore (illustrative)
1031     /// extern crate foo;
1032     /// extern crate bar as foo;
1033     /// ```
1034     fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1035         // Accept `extern crate name-like-this` for better diagnostics
1036         let orig_name = self.parse_crate_name_with_dashes()?;
1037         let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1038             (rename, Some(orig_name.name))
1039         } else {
1040             (orig_name, None)
1041         };
1042         self.expect_semi()?;
1043         Ok((item_name, ItemKind::ExternCrate(orig_name)))
1044     }
1045
1046     fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1047         let ident = if self.token.is_keyword(kw::SelfLower) {
1048             self.parse_path_segment_ident()
1049         } else {
1050             self.parse_ident()
1051         }?;
1052
1053         let dash = token::BinOp(token::BinOpToken::Minus);
1054         if self.token != dash {
1055             return Ok(ident);
1056         }
1057
1058         // Accept `extern crate name-like-this` for better diagnostics.
1059         let mut dashes = vec![];
1060         let mut idents = vec![];
1061         while self.eat(&dash) {
1062             dashes.push(self.prev_token.span);
1063             idents.push(self.parse_ident()?);
1064         }
1065
1066         let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1067         let mut fixed_name = ident.name.to_string();
1068         for part in idents {
1069             write!(fixed_name, "_{}", part.name).unwrap();
1070         }
1071
1072         self.sess.emit_err(ExternCrateNameWithDashes {
1073             span: fixed_name_sp,
1074             sugg: ExternCrateNameWithDashesSugg { dashes },
1075         });
1076
1077         Ok(Ident::from_str_and_span(&fixed_name, fixed_name_sp))
1078     }
1079
1080     /// Parses `extern` for foreign ABIs modules.
1081     ///
1082     /// `extern` is expected to have been consumed before calling this method.
1083     ///
1084     /// # Examples
1085     ///
1086     /// ```ignore (only-for-syntax-highlight)
1087     /// extern "C" {}
1088     /// extern {}
1089     /// ```
1090     fn parse_item_foreign_mod(
1091         &mut self,
1092         attrs: &mut AttrVec,
1093         mut unsafety: Unsafe,
1094     ) -> PResult<'a, ItemInfo> {
1095         let abi = self.parse_abi(); // ABI?
1096         if unsafety == Unsafe::No
1097             && self.token.is_keyword(kw::Unsafe)
1098             && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1099         {
1100             let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1101             err.emit();
1102             unsafety = Unsafe::Yes(self.token.span);
1103             self.eat_keyword(kw::Unsafe);
1104         }
1105         let module = ast::ForeignMod {
1106             unsafety,
1107             abi,
1108             items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1109         };
1110         Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1111     }
1112
1113     /// Parses a foreign item (one in an `extern { ... }` block).
1114     pub fn parse_foreign_item(
1115         &mut self,
1116         force_collect: ForceCollect,
1117     ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1118         let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1119         Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1120             |Item { attrs, id, span, vis, ident, kind, tokens }| {
1121                 let kind = match ForeignItemKind::try_from(kind) {
1122                     Ok(kind) => kind,
1123                     Err(kind) => match kind {
1124                         ItemKind::Const(_, a, b) => {
1125                             self.sess.emit_err(ExternItemCannotBeConst {
1126                                 ident_span: ident.span,
1127                                 const_span: span.with_hi(ident.span.lo()),
1128                             });
1129                             ForeignItemKind::Static(a, Mutability::Not, b)
1130                         }
1131                         _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1132                     },
1133                 };
1134                 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1135             },
1136         ))
1137     }
1138
1139     fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1140         // FIXME(#100717): needs variant for each `ItemKind` (instead of using `ItemKind::descr()`)
1141         let span = self.sess.source_map().guess_head_span(span);
1142         let descr = kind.descr();
1143         self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1144             .help(&format!("consider moving the {descr} out to a nearby module scope"))
1145             .emit();
1146         None
1147     }
1148
1149     fn is_unsafe_foreign_mod(&self) -> bool {
1150         self.token.is_keyword(kw::Unsafe)
1151             && self.is_keyword_ahead(1, &[kw::Extern])
1152             && self.look_ahead(
1153                 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1154                 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1155             )
1156     }
1157
1158     fn is_static_global(&mut self) -> bool {
1159         if self.check_keyword(kw::Static) {
1160             // Check if this could be a closure.
1161             !self.look_ahead(1, |token| {
1162                 if token.is_keyword(kw::Move) {
1163                     return true;
1164                 }
1165                 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1166             })
1167         } else {
1168             false
1169         }
1170     }
1171
1172     /// Recover on `const mut` with `const` already eaten.
1173     fn recover_const_mut(&mut self, const_span: Span) {
1174         if self.eat_keyword(kw::Mut) {
1175             let span = self.prev_token.span;
1176             self.sess.emit_err(ConstGlobalCannotBeMutable { ident_span: span, const_span });
1177         } else if self.eat_keyword(kw::Let) {
1178             let span = self.prev_token.span;
1179             self.sess.emit_err(ConstLetMutuallyExclusive { span: const_span.to(span) });
1180         }
1181     }
1182
1183     /// Recover on `const impl` with `const` already eaten.
1184     fn recover_const_impl(
1185         &mut self,
1186         const_span: Span,
1187         attrs: &mut AttrVec,
1188         defaultness: Defaultness,
1189     ) -> PResult<'a, ItemInfo> {
1190         let impl_span = self.token.span;
1191         let mut err = self.expected_ident_found();
1192
1193         // Only try to recover if this is implementing a trait for a type
1194         let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1195             Ok(impl_info) => impl_info,
1196             Err(recovery_error) => {
1197                 // Recovery failed, raise the "expected identifier" error
1198                 recovery_error.cancel();
1199                 return Err(err);
1200             }
1201         };
1202
1203         match &mut impl_info.1 {
1204             ItemKind::Impl(box Impl { of_trait: Some(trai), constness, .. }) => {
1205                 *constness = Const::Yes(const_span);
1206
1207                 let before_trait = trai.path.span.shrink_to_lo();
1208                 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1209                 err.multipart_suggestion(
1210                     "you might have meant to write a const trait impl",
1211                     vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1212                     Applicability::MaybeIncorrect,
1213                 )
1214                 .emit();
1215             }
1216             ItemKind::Impl { .. } => return Err(err),
1217             _ => unreachable!(),
1218         }
1219
1220         Ok(impl_info)
1221     }
1222
1223     /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1224     /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1225     ///
1226     /// When `m` is `"const"`, `$ident` may also be `"_"`.
1227     fn parse_item_global(
1228         &mut self,
1229         m: Option<Mutability>,
1230     ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1231         let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1232
1233         // Parse the type of a `const` or `static mut?` item.
1234         // That is, the `":" $ty` fragment.
1235         let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1236         {
1237             // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1238             (true, false) => self.parse_ty()?,
1239             (colon, _) => self.recover_missing_const_type(colon, m),
1240         };
1241
1242         let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1243         self.expect_semi()?;
1244         Ok((id, ty, expr))
1245     }
1246
1247     /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1248     /// This means that the type is missing.
1249     fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1250         // Construct the error and stash it away with the hope
1251         // that typeck will later enrich the error with a type.
1252         let kind = match m {
1253             Some(Mutability::Mut) => "static mut",
1254             Some(Mutability::Not) => "static",
1255             None => "const",
1256         };
1257
1258         let colon = match colon_present {
1259             true => "",
1260             false => ":",
1261         };
1262
1263         let span = self.prev_token.span.shrink_to_hi();
1264         let err: DiagnosticBuilder<'_, ErrorGuaranteed> =
1265             MissingConstType { span, colon, kind }.into_diagnostic(&self.sess.span_diagnostic);
1266         err.stash(span, StashKey::ItemNoType);
1267
1268         // The user intended that the type be inferred,
1269         // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1270         P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1271     }
1272
1273     /// Parses an enum declaration.
1274     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1275         if self.token.is_keyword(kw::Struct) {
1276             let span = self.prev_token.span.to(self.token.span);
1277             let err = EnumStructMutuallyExclusive { span };
1278             if self.look_ahead(1, |t| t.is_ident()) {
1279                 self.bump();
1280                 self.sess.emit_err(err);
1281             } else {
1282                 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1283             }
1284         }
1285
1286         let id = self.parse_ident()?;
1287         let mut generics = self.parse_generics()?;
1288         generics.where_clause = self.parse_where_clause()?;
1289
1290         // Possibly recover `enum Foo;` instead of `enum Foo {}`
1291         let (variants, _) = if self.token == TokenKind::Semi {
1292             self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1293             self.bump();
1294             (vec![], false)
1295         } else {
1296             self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1297                 |mut e| {
1298                     e.span_label(id.span, "while parsing this enum");
1299                     self.recover_stmt();
1300                     e
1301                 },
1302             )?
1303         };
1304
1305         let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1306         Ok((id, ItemKind::Enum(enum_definition, generics)))
1307     }
1308
1309     fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1310         self.recover_diff_marker();
1311         let variant_attrs = self.parse_outer_attributes()?;
1312         self.recover_diff_marker();
1313         self.collect_tokens_trailing_token(
1314             variant_attrs,
1315             ForceCollect::No,
1316             |this, variant_attrs| {
1317                 let vlo = this.token.span;
1318
1319                 let vis = this.parse_visibility(FollowedByType::No)?;
1320                 if !this.recover_nested_adt_item(kw::Enum)? {
1321                     return Ok((None, TrailingToken::None));
1322                 }
1323                 let ident = this.parse_field_ident("enum", vlo)?;
1324
1325                 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1326                     // Parse a struct variant.
1327                     let (fields, recovered) =
1328                         this.parse_record_struct_body("struct", ident.span, false)?;
1329                     VariantData::Struct(fields, recovered)
1330                 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1331                     VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1332                 } else {
1333                     VariantData::Unit(DUMMY_NODE_ID)
1334                 };
1335
1336                 let disr_expr =
1337                     if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1338
1339                 let vr = ast::Variant {
1340                     ident,
1341                     vis,
1342                     id: DUMMY_NODE_ID,
1343                     attrs: variant_attrs,
1344                     data: struct_def,
1345                     disr_expr,
1346                     span: vlo.to(this.prev_token.span),
1347                     is_placeholder: false,
1348                 };
1349
1350                 Ok((Some(vr), TrailingToken::MaybeComma))
1351             },
1352         ).map_err(|mut err|{
1353             err.help("enum variants can be `Variant`, `Variant = <integer>`, `Variant(Type, ..., TypeN)` or `Variant { fields: Types }`");
1354             err
1355         })
1356     }
1357
1358     /// Parses `struct Foo { ... }`.
1359     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1360         let class_name = self.parse_ident()?;
1361
1362         let mut generics = self.parse_generics()?;
1363
1364         // There is a special case worth noting here, as reported in issue #17904.
1365         // If we are parsing a tuple struct it is the case that the where clause
1366         // should follow the field list. Like so:
1367         //
1368         // struct Foo<T>(T) where T: Copy;
1369         //
1370         // If we are parsing a normal record-style struct it is the case
1371         // that the where clause comes before the body, and after the generics.
1372         // So if we look ahead and see a brace or a where-clause we begin
1373         // parsing a record style struct.
1374         //
1375         // Otherwise if we look ahead and see a paren we parse a tuple-style
1376         // struct.
1377
1378         let vdata = if self.token.is_keyword(kw::Where) {
1379             let tuple_struct_body;
1380             (generics.where_clause, tuple_struct_body) =
1381                 self.parse_struct_where_clause(class_name, generics.span)?;
1382
1383             if let Some(body) = tuple_struct_body {
1384                 // If we see a misplaced tuple struct body: `struct Foo<T> where T: Copy, (T);`
1385                 let body = VariantData::Tuple(body, DUMMY_NODE_ID);
1386                 self.expect_semi()?;
1387                 body
1388             } else if self.eat(&token::Semi) {
1389                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1390                 VariantData::Unit(DUMMY_NODE_ID)
1391             } else {
1392                 // If we see: `struct Foo<T> where T: Copy { ... }`
1393                 let (fields, recovered) = self.parse_record_struct_body(
1394                     "struct",
1395                     class_name.span,
1396                     generics.where_clause.has_where_token,
1397                 )?;
1398                 VariantData::Struct(fields, recovered)
1399             }
1400         // No `where` so: `struct Foo<T>;`
1401         } else if self.eat(&token::Semi) {
1402             VariantData::Unit(DUMMY_NODE_ID)
1403         // Record-style struct definition
1404         } else if self.token == token::OpenDelim(Delimiter::Brace) {
1405             let (fields, recovered) = self.parse_record_struct_body(
1406                 "struct",
1407                 class_name.span,
1408                 generics.where_clause.has_where_token,
1409             )?;
1410             VariantData::Struct(fields, recovered)
1411         // Tuple-style struct definition with optional where-clause.
1412         } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1413             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1414             generics.where_clause = self.parse_where_clause()?;
1415             self.expect_semi()?;
1416             body
1417         } else {
1418             let err = UnexpectedTokenAfterStructName::new(self.token.span, self.token.clone());
1419             return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1420         };
1421
1422         Ok((class_name, ItemKind::Struct(vdata, generics)))
1423     }
1424
1425     /// Parses `union Foo { ... }`.
1426     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1427         let class_name = self.parse_ident()?;
1428
1429         let mut generics = self.parse_generics()?;
1430
1431         let vdata = if self.token.is_keyword(kw::Where) {
1432             generics.where_clause = self.parse_where_clause()?;
1433             let (fields, recovered) = self.parse_record_struct_body(
1434                 "union",
1435                 class_name.span,
1436                 generics.where_clause.has_where_token,
1437             )?;
1438             VariantData::Struct(fields, recovered)
1439         } else if self.token == token::OpenDelim(Delimiter::Brace) {
1440             let (fields, recovered) = self.parse_record_struct_body(
1441                 "union",
1442                 class_name.span,
1443                 generics.where_clause.has_where_token,
1444             )?;
1445             VariantData::Struct(fields, recovered)
1446         } else {
1447             let token_str = super::token_descr(&self.token);
1448             let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1449             let mut err = self.struct_span_err(self.token.span, msg);
1450             err.span_label(self.token.span, "expected `where` or `{` after union name");
1451             return Err(err);
1452         };
1453
1454         Ok((class_name, ItemKind::Union(vdata, generics)))
1455     }
1456
1457     fn parse_record_struct_body(
1458         &mut self,
1459         adt_ty: &str,
1460         ident_span: Span,
1461         parsed_where: bool,
1462     ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1463         let mut fields = Vec::new();
1464         let mut recovered = false;
1465         if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1466             while self.token != token::CloseDelim(Delimiter::Brace) {
1467                 let field = self.parse_field_def(adt_ty).map_err(|e| {
1468                     self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1469                     recovered = true;
1470                     e
1471                 });
1472                 match field {
1473                     Ok(field) => fields.push(field),
1474                     Err(mut err) => {
1475                         err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1476                         err.emit();
1477                         break;
1478                     }
1479                 }
1480             }
1481             self.eat(&token::CloseDelim(Delimiter::Brace));
1482         } else {
1483             let token_str = super::token_descr(&self.token);
1484             let msg = &format!(
1485                 "expected {}`{{` after struct name, found {}",
1486                 if parsed_where { "" } else { "`where`, or " },
1487                 token_str
1488             );
1489             let mut err = self.struct_span_err(self.token.span, msg);
1490             err.span_label(
1491                 self.token.span,
1492                 format!(
1493                     "expected {}`{{` after struct name",
1494                     if parsed_where { "" } else { "`where`, or " }
1495                 ),
1496             );
1497             return Err(err);
1498         }
1499
1500         Ok((fields, recovered))
1501     }
1502
1503     pub(super) fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1504         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1505         // Unit like structs are handled in parse_item_struct function
1506         self.parse_paren_comma_seq(|p| {
1507             let attrs = p.parse_outer_attributes()?;
1508             p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1509                 let mut snapshot = None;
1510                 if p.is_diff_marker(&TokenKind::BinOp(token::Shl), &TokenKind::Lt) {
1511                     // Account for `<<<<<<<` diff markers. We can't proactively error here because
1512                     // that can be a valid type start, so we snapshot and reparse only we've
1513                     // encountered another parse error.
1514                     snapshot = Some(p.create_snapshot_for_diagnostic());
1515                 }
1516                 let lo = p.token.span;
1517                 let vis = match p.parse_visibility(FollowedByType::Yes) {
1518                     Ok(vis) => vis,
1519                     Err(err) => {
1520                         if let Some(ref mut snapshot) = snapshot {
1521                             snapshot.recover_diff_marker();
1522                         }
1523                         return Err(err);
1524                     }
1525                 };
1526                 let ty = match p.parse_ty() {
1527                     Ok(ty) => ty,
1528                     Err(err) => {
1529                         if let Some(ref mut snapshot) = snapshot {
1530                             snapshot.recover_diff_marker();
1531                         }
1532                         return Err(err);
1533                     }
1534                 };
1535
1536                 Ok((
1537                     FieldDef {
1538                         span: lo.to(ty.span),
1539                         vis,
1540                         ident: None,
1541                         id: DUMMY_NODE_ID,
1542                         ty,
1543                         attrs,
1544                         is_placeholder: false,
1545                     },
1546                     TrailingToken::MaybeComma,
1547                 ))
1548             })
1549         })
1550         .map(|(r, _)| r)
1551     }
1552
1553     /// Parses an element of a struct declaration.
1554     fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1555         self.recover_diff_marker();
1556         let attrs = self.parse_outer_attributes()?;
1557         self.recover_diff_marker();
1558         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1559             let lo = this.token.span;
1560             let vis = this.parse_visibility(FollowedByType::No)?;
1561             Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1562         })
1563     }
1564
1565     /// Parses a structure field declaration.
1566     fn parse_single_struct_field(
1567         &mut self,
1568         adt_ty: &str,
1569         lo: Span,
1570         vis: Visibility,
1571         attrs: AttrVec,
1572     ) -> PResult<'a, FieldDef> {
1573         let mut seen_comma: bool = false;
1574         let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1575         if self.token == token::Comma {
1576             seen_comma = true;
1577         }
1578         if self.eat(&token::Semi) {
1579             let sp = self.prev_token.span;
1580             let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1581             err.span_suggestion_short(
1582                 sp,
1583                 "replace `;` with `,`",
1584                 ",",
1585                 Applicability::MachineApplicable,
1586             );
1587             return Err(err);
1588         }
1589         match self.token.kind {
1590             token::Comma => {
1591                 self.bump();
1592             }
1593             token::CloseDelim(Delimiter::Brace) => {}
1594             token::DocComment(..) => {
1595                 let previous_span = self.prev_token.span;
1596                 let mut err = DocCommentDoesNotDocumentAnything {
1597                     span: self.token.span,
1598                     missing_comma: None,
1599                 };
1600                 self.bump(); // consume the doc comment
1601                 let comma_after_doc_seen = self.eat(&token::Comma);
1602                 // `seen_comma` is always false, because we are inside doc block
1603                 // condition is here to make code more readable
1604                 if !seen_comma && comma_after_doc_seen {
1605                     seen_comma = true;
1606                 }
1607                 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1608                     self.sess.emit_err(err);
1609                 } else {
1610                     if !seen_comma {
1611                         let sp = previous_span.shrink_to_hi();
1612                         err.missing_comma = Some(sp);
1613                     }
1614                     return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1615                 }
1616             }
1617             _ => {
1618                 let sp = self.prev_token.span.shrink_to_hi();
1619                 let mut err = self.struct_span_err(
1620                     sp,
1621                     &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1622                 );
1623
1624                 // Try to recover extra trailing angle brackets
1625                 let mut recovered = false;
1626                 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1627                     if let Some(last_segment) = segments.last() {
1628                         recovered = self.check_trailing_angle_brackets(
1629                             last_segment,
1630                             &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1631                         );
1632                         if recovered {
1633                             // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1634                             // after the comma
1635                             self.eat(&token::Comma);
1636                             // `check_trailing_angle_brackets` already emitted a nicer error
1637                             // NOTE(eddyb) this was `.cancel()`, but `err`
1638                             // gets returned, so we can't fully defuse it.
1639                             err.delay_as_bug();
1640                         }
1641                     }
1642                 }
1643
1644                 if self.token.is_ident()
1645                     || (self.token.kind == TokenKind::Pound
1646                         && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1647                 {
1648                     // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1649                     // emit the diagnostic and keep going
1650                     err.span_suggestion(
1651                         sp,
1652                         "try adding a comma",
1653                         ",",
1654                         Applicability::MachineApplicable,
1655                     );
1656                     err.emit();
1657                     recovered = true;
1658                 }
1659
1660                 if recovered {
1661                     // Make sure an error was emitted (either by recovering an angle bracket,
1662                     // or by finding an identifier as the next token), since we're
1663                     // going to continue parsing
1664                     assert!(self.sess.span_diagnostic.has_errors().is_some());
1665                 } else {
1666                     return Err(err);
1667                 }
1668             }
1669         }
1670         Ok(a_var)
1671     }
1672
1673     fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1674         if let Err(mut err) = self.expect(&token::Colon) {
1675             let sm = self.sess.source_map();
1676             let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1677             let semi_typo = self.token.kind == token::Semi
1678                 && self.look_ahead(1, |t| {
1679                     t.is_path_start()
1680                     // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1681                     // when there's no type and `;` was used instead of a comma.
1682                     && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1683                         (Ok(l), Ok(r)) => l.line == r.line,
1684                         _ => true,
1685                     }
1686                 });
1687             if eq_typo || semi_typo {
1688                 self.bump();
1689                 // Gracefully handle small typos.
1690                 err.span_suggestion_short(
1691                     self.prev_token.span,
1692                     "field names and their types are separated with `:`",
1693                     ":",
1694                     Applicability::MachineApplicable,
1695                 );
1696                 err.emit();
1697             } else {
1698                 return Err(err);
1699             }
1700         }
1701         Ok(())
1702     }
1703
1704     /// Parses a structure field.
1705     fn parse_name_and_ty(
1706         &mut self,
1707         adt_ty: &str,
1708         lo: Span,
1709         vis: Visibility,
1710         attrs: AttrVec,
1711     ) -> PResult<'a, FieldDef> {
1712         let name = self.parse_field_ident(adt_ty, lo)?;
1713         self.expect_field_ty_separator()?;
1714         let ty = self.parse_ty()?;
1715         if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1716             self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1717                 .span_suggestion_verbose(
1718                     self.token.span,
1719                     "write a path separator here",
1720                     "::",
1721                     Applicability::MaybeIncorrect,
1722                 )
1723                 .emit();
1724         }
1725         if self.token.kind == token::Eq {
1726             self.bump();
1727             let const_expr = self.parse_anon_const_expr()?;
1728             let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1729             self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1730                 .span_suggestion(
1731                     sp,
1732                     "remove this unsupported default value",
1733                     "",
1734                     Applicability::MachineApplicable,
1735                 )
1736                 .emit();
1737         }
1738         Ok(FieldDef {
1739             span: lo.to(self.prev_token.span),
1740             ident: Some(name),
1741             vis,
1742             id: DUMMY_NODE_ID,
1743             ty,
1744             attrs,
1745             is_placeholder: false,
1746         })
1747     }
1748
1749     /// Parses a field identifier. Specialized version of `parse_ident_common`
1750     /// for better diagnostics and suggestions.
1751     fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1752         let (ident, is_raw) = self.ident_or_err()?;
1753         if !is_raw && ident.is_reserved() {
1754             let snapshot = self.create_snapshot_for_diagnostic();
1755             let err = if self.check_fn_front_matter(false, Case::Sensitive) {
1756                 let inherited_vis = Visibility {
1757                     span: rustc_span::DUMMY_SP,
1758                     kind: VisibilityKind::Inherited,
1759                     tokens: None,
1760                 };
1761                 // We use `parse_fn` to get a span for the function
1762                 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1763                 match self.parse_fn(
1764                     &mut AttrVec::new(),
1765                     fn_parse_mode,
1766                     lo,
1767                     &inherited_vis,
1768                     Case::Insensitive,
1769                 ) {
1770                     Ok(_) => {
1771                         let mut err = self.struct_span_err(
1772                             lo.to(self.prev_token.span),
1773                             &format!("functions are not allowed in {adt_ty} definitions"),
1774                         );
1775                         err.help(
1776                             "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1777                         );
1778                         err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1779                         err
1780                     }
1781                     Err(err) => {
1782                         err.cancel();
1783                         self.restore_snapshot(snapshot);
1784                         self.expected_ident_found()
1785                     }
1786                 }
1787             } else if self.eat_keyword(kw::Struct) {
1788                 match self.parse_item_struct() {
1789                     Ok((ident, _)) => {
1790                         let mut err = self.struct_span_err(
1791                             lo.with_hi(ident.span.hi()),
1792                             &format!("structs are not allowed in {adt_ty} definitions"),
1793                         );
1794                         err.help("consider creating a new `struct` definition instead of nesting");
1795                         err
1796                     }
1797                     Err(err) => {
1798                         err.cancel();
1799                         self.restore_snapshot(snapshot);
1800                         self.expected_ident_found()
1801                     }
1802                 }
1803             } else {
1804                 let mut err = self.expected_ident_found();
1805                 if self.eat_keyword_noexpect(kw::Let)
1806                     && let removal_span = self.prev_token.span.until(self.token.span)
1807                     && let Ok(ident) = self.parse_ident_common(false)
1808                         // Cancel this error, we don't need it.
1809                         .map_err(|err| err.cancel())
1810                     && self.token.kind == TokenKind::Colon
1811                 {
1812                     err.span_suggestion(
1813                         removal_span,
1814                         "remove this `let` keyword",
1815                         String::new(),
1816                         Applicability::MachineApplicable,
1817                     );
1818                     err.note("the `let` keyword is not allowed in `struct` fields");
1819                     err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1820                     err.emit();
1821                     return Ok(ident);
1822                 } else {
1823                     self.restore_snapshot(snapshot);
1824                 }
1825                 err
1826             };
1827             return Err(err);
1828         }
1829         self.bump();
1830         Ok(ident)
1831     }
1832
1833     /// Parses a declarative macro 2.0 definition.
1834     /// The `macro` keyword has already been parsed.
1835     /// ```ebnf
1836     /// MacBody = "{" TOKEN_STREAM "}" ;
1837     /// MacParams = "(" TOKEN_STREAM ")" ;
1838     /// DeclMac = "macro" Ident MacParams? MacBody ;
1839     /// ```
1840     fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1841         let ident = self.parse_ident()?;
1842         let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1843             self.parse_delim_args()? // `MacBody`
1844         } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1845             let params = self.parse_token_tree(); // `MacParams`
1846             let pspan = params.span();
1847             if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1848                 return self.unexpected();
1849             }
1850             let body = self.parse_token_tree(); // `MacBody`
1851             // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1852             let bspan = body.span();
1853             let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1854             let tokens = TokenStream::new(vec![params, arrow, body]);
1855             let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1856             P(DelimArgs { dspan, delim: MacDelimiter::Brace, tokens })
1857         } else {
1858             return self.unexpected();
1859         };
1860
1861         self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1862         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1863     }
1864
1865     /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1866     fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1867         if self.check_keyword(kw::MacroRules) {
1868             let macro_rules_span = self.token.span;
1869
1870             if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1871                 return IsMacroRulesItem::Yes { has_bang: true };
1872             } else if self.look_ahead(1, |t| (t.is_ident())) {
1873                 // macro_rules foo
1874                 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1875                     .span_suggestion(
1876                         macro_rules_span,
1877                         "add a `!`",
1878                         "macro_rules!",
1879                         Applicability::MachineApplicable,
1880                     )
1881                     .emit();
1882
1883                 return IsMacroRulesItem::Yes { has_bang: false };
1884             }
1885         }
1886
1887         IsMacroRulesItem::No
1888     }
1889
1890     /// Parses a `macro_rules! foo { ... }` declarative macro.
1891     fn parse_item_macro_rules(
1892         &mut self,
1893         vis: &Visibility,
1894         has_bang: bool,
1895     ) -> PResult<'a, ItemInfo> {
1896         self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1897
1898         if has_bang {
1899             self.expect(&token::Not)?; // `!`
1900         }
1901         let ident = self.parse_ident()?;
1902
1903         if self.eat(&token::Not) {
1904             // Handle macro_rules! foo!
1905             let span = self.prev_token.span;
1906             self.struct_span_err(span, "macro names aren't followed by a `!`")
1907                 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1908                 .emit();
1909         }
1910
1911         let body = self.parse_delim_args()?;
1912         self.eat_semi_for_macro_if_needed(&body);
1913         self.complain_if_pub_macro(vis, true);
1914
1915         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1916     }
1917
1918     /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1919     /// If that's not the case, emit an error.
1920     fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1921         if let VisibilityKind::Inherited = vis.kind {
1922             return;
1923         }
1924
1925         let vstr = pprust::vis_to_string(vis);
1926         let vstr = vstr.trim_end();
1927         if macro_rules {
1928             let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1929             self.struct_span_err(vis.span, &msg)
1930                 .span_suggestion(
1931                     vis.span,
1932                     "try exporting the macro",
1933                     "#[macro_export]",
1934                     Applicability::MaybeIncorrect, // speculative
1935                 )
1936                 .emit();
1937         } else {
1938             self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1939                 .span_suggestion(
1940                     vis.span,
1941                     "remove the visibility",
1942                     "",
1943                     Applicability::MachineApplicable,
1944                 )
1945                 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1946                 .emit();
1947         }
1948     }
1949
1950     fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs) {
1951         if args.need_semicolon() && !self.eat(&token::Semi) {
1952             self.report_invalid_macro_expansion_item(args);
1953         }
1954     }
1955
1956     fn report_invalid_macro_expansion_item(&self, args: &DelimArgs) {
1957         let span = args.dspan.entire();
1958         let mut err = self.struct_span_err(
1959             span,
1960             "macros that expand to items must be delimited with braces or followed by a semicolon",
1961         );
1962         // FIXME: This will make us not emit the help even for declarative
1963         // macros within the same crate (that we can fix), which is sad.
1964         if !span.from_expansion() {
1965             if self.unclosed_delims.is_empty() {
1966                 let DelimSpan { open, close } = args.dspan;
1967                 err.multipart_suggestion(
1968                     "change the delimiters to curly braces",
1969                     vec![(open, "{".to_string()), (close, '}'.to_string())],
1970                     Applicability::MaybeIncorrect,
1971                 );
1972             } else {
1973                 err.span_suggestion(
1974                     span,
1975                     "change the delimiters to curly braces",
1976                     " { /* items */ }",
1977                     Applicability::HasPlaceholders,
1978                 );
1979             }
1980             err.span_suggestion(
1981                 span.shrink_to_hi(),
1982                 "add a semicolon",
1983                 ';',
1984                 Applicability::MaybeIncorrect,
1985             );
1986         }
1987         err.emit();
1988     }
1989
1990     /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1991     /// it is, we try to parse the item and report error about nested types.
1992     fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1993         if (self.token.is_keyword(kw::Enum)
1994             || self.token.is_keyword(kw::Struct)
1995             || self.token.is_keyword(kw::Union))
1996             && self.look_ahead(1, |t| t.is_ident())
1997         {
1998             let kw_token = self.token.clone();
1999             let kw_str = pprust::token_to_string(&kw_token);
2000             let item = self.parse_item(ForceCollect::No)?;
2001
2002             self.struct_span_err(
2003                 kw_token.span,
2004                 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
2005             )
2006             .span_suggestion(
2007                 item.unwrap().span,
2008                 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2009                 "",
2010                 Applicability::MaybeIncorrect,
2011             )
2012             .emit();
2013             // We successfully parsed the item but we must inform the caller about nested problem.
2014             return Ok(false);
2015         }
2016         Ok(true)
2017     }
2018 }
2019
2020 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2021 ///
2022 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2023 ///
2024 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2025 /// were allowed to omit parameter names. In 2018, they became required.
2026 type ReqName = fn(Edition) -> bool;
2027
2028 /// Parsing configuration for functions.
2029 ///
2030 /// The syntax of function items is slightly different within trait definitions,
2031 /// impl blocks, and modules. It is still parsed using the same code, just with
2032 /// different flags set, so that even when the input is wrong and produces a parse
2033 /// error, it still gets into the AST and the rest of the parser and
2034 /// type checker can run.
2035 #[derive(Clone, Copy)]
2036 pub(crate) struct FnParseMode {
2037     /// A function pointer that decides if, per-parameter `p`, `p` must have a
2038     /// pattern or just a type. This field affects parsing of the parameters list.
2039     ///
2040     /// ```text
2041     /// fn foo(alef: A) -> X { X::new() }
2042     ///        -----^^ affects parsing this part of the function signature
2043     ///        |
2044     ///        if req_name returns false, then this name is optional
2045     ///
2046     /// fn bar(A) -> X;
2047     ///        ^
2048     ///        |
2049     ///        if req_name returns true, this is an error
2050     /// ```
2051     ///
2052     /// Calling this function pointer should only return false if:
2053     ///
2054     ///   * The item is being parsed inside of a trait definition.
2055     ///     Within an impl block or a module, it should always evaluate
2056     ///     to true.
2057     ///   * The span is from Edition 2015. In particular, you can get a
2058     ///     2015 span inside a 2021 crate using macros.
2059     pub req_name: ReqName,
2060     /// If this flag is set to `true`, then plain, semicolon-terminated function
2061     /// prototypes are not allowed here.
2062     ///
2063     /// ```text
2064     /// fn foo(alef: A) -> X { X::new() }
2065     ///                      ^^^^^^^^^^^^
2066     ///                      |
2067     ///                      this is always allowed
2068     ///
2069     /// fn bar(alef: A, bet: B) -> X;
2070     ///                             ^
2071     ///                             |
2072     ///                             if req_body is set to true, this is an error
2073     /// ```
2074     ///
2075     /// This field should only be set to false if the item is inside of a trait
2076     /// definition or extern block. Within an impl block or a module, it should
2077     /// always be set to true.
2078     pub req_body: bool,
2079 }
2080
2081 /// Parsing of functions and methods.
2082 impl<'a> Parser<'a> {
2083     /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2084     fn parse_fn(
2085         &mut self,
2086         attrs: &mut AttrVec,
2087         fn_parse_mode: FnParseMode,
2088         sig_lo: Span,
2089         vis: &Visibility,
2090         case: Case,
2091     ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2092         let fn_span = self.token.span;
2093         let header = self.parse_fn_front_matter(vis, case)?; // `const ... fn`
2094         let ident = self.parse_ident()?; // `foo`
2095         let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2096         let decl = match self.parse_fn_decl(
2097             fn_parse_mode.req_name,
2098             AllowPlus::Yes,
2099             RecoverReturnSign::Yes,
2100         ) {
2101             Ok(decl) => decl,
2102             Err(old_err) => {
2103                 // If we see `for Ty ...` then user probably meant `impl` item.
2104                 if self.token.is_keyword(kw::For) {
2105                     old_err.cancel();
2106                     return Err(self.sess.create_err(FnTypoWithImpl { fn_span }));
2107                 } else {
2108                     return Err(old_err);
2109                 }
2110             }
2111         };
2112         generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2113
2114         let mut sig_hi = self.prev_token.span;
2115         let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2116         let fn_sig_span = sig_lo.to(sig_hi);
2117         Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2118     }
2119
2120     /// Parse the "body" of a function.
2121     /// This can either be `;` when there's no body,
2122     /// or e.g. a block when the function is a provided one.
2123     fn parse_fn_body(
2124         &mut self,
2125         attrs: &mut AttrVec,
2126         ident: &Ident,
2127         sig_hi: &mut Span,
2128         req_body: bool,
2129     ) -> PResult<'a, Option<P<Block>>> {
2130         let has_semi = if req_body {
2131             self.token.kind == TokenKind::Semi
2132         } else {
2133             // Only include `;` in list of expected tokens if body is not required
2134             self.check(&TokenKind::Semi)
2135         };
2136         let (inner_attrs, body) = if has_semi {
2137             // Include the trailing semicolon in the span of the signature
2138             self.expect_semi()?;
2139             *sig_hi = self.prev_token.span;
2140             (AttrVec::new(), None)
2141         } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2142             self.parse_block_common(self.token.span, BlockCheckMode::Default, false)
2143                 .map(|(attrs, body)| (attrs, Some(body)))?
2144         } else if self.token.kind == token::Eq {
2145             // Recover `fn foo() = $expr;`.
2146             self.bump(); // `=`
2147             let eq_sp = self.prev_token.span;
2148             let _ = self.parse_expr()?;
2149             self.expect_semi()?; // `;`
2150             let span = eq_sp.to(self.prev_token.span);
2151             self.struct_span_err(span, "function body cannot be `= expression;`")
2152                 .multipart_suggestion(
2153                     "surround the expression with `{` and `}` instead of `=` and `;`",
2154                     vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2155                     Applicability::MachineApplicable,
2156                 )
2157                 .emit();
2158             (AttrVec::new(), Some(self.mk_block_err(span)))
2159         } else {
2160             let expected = if req_body {
2161                 &[token::OpenDelim(Delimiter::Brace)][..]
2162             } else {
2163                 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2164             };
2165             if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2166                 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2167                     // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2168                     // the AST for typechecking.
2169                     err.span_label(ident.span, "while parsing this `fn`");
2170                     err.emit();
2171                 } else {
2172                     return Err(err);
2173                 }
2174             }
2175             (AttrVec::new(), None)
2176         };
2177         attrs.extend(inner_attrs);
2178         Ok(body)
2179     }
2180
2181     /// Is the current token the start of an `FnHeader` / not a valid parse?
2182     ///
2183     /// `check_pub` adds additional `pub` to the checks in case users place it
2184     /// wrongly, can be used to ensure `pub` never comes after `default`.
2185     pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2186         // We use an over-approximation here.
2187         // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2188         // `pub` is added in case users got confused with the ordering like `async pub fn`,
2189         // only if it wasn't preceded by `default` as `default pub` is invalid.
2190         let quals: &[Symbol] = if check_pub {
2191             &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2192         } else {
2193             &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2194         };
2195         self.check_keyword_case(kw::Fn, case) // Definitely an `fn`.
2196             // `$qual fn` or `$qual $qual`:
2197             || quals.iter().any(|&kw| self.check_keyword_case(kw, case))
2198                 && self.look_ahead(1, |t| {
2199                     // `$qual fn`, e.g. `const fn` or `async fn`.
2200                     t.is_keyword_case(kw::Fn, case)
2201                     // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2202                     || (
2203                         (
2204                             t.is_non_raw_ident_where(|i|
2205                                 quals.contains(&i.name)
2206                                     // Rule out 2015 `const async: T = val`.
2207                                     && i.is_reserved()
2208                             )
2209                             || case == Case::Insensitive
2210                                 && t.is_non_raw_ident_where(|i| quals.iter().any(|qual| qual.as_str() == i.name.as_str().to_lowercase()))
2211                         )
2212                         // Rule out unsafe extern block.
2213                         && !self.is_unsafe_foreign_mod())
2214                 })
2215             // `extern ABI fn`
2216             || self.check_keyword_case(kw::Extern, case)
2217                 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2218                 && self.look_ahead(2, |t| t.is_keyword_case(kw::Fn, case))
2219     }
2220
2221     /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2222     /// up to and including the `fn` keyword. The formal grammar is:
2223     ///
2224     /// ```text
2225     /// Extern = "extern" StringLit? ;
2226     /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2227     /// FnFrontMatter = FnQual "fn" ;
2228     /// ```
2229     ///
2230     /// `vis` represents the visibility that was already parsed, if any. Use
2231     /// `Visibility::Inherited` when no visibility is known.
2232     pub(super) fn parse_fn_front_matter(
2233         &mut self,
2234         orig_vis: &Visibility,
2235         case: Case,
2236     ) -> PResult<'a, FnHeader> {
2237         let sp_start = self.token.span;
2238         let constness = self.parse_constness(case);
2239
2240         let async_start_sp = self.token.span;
2241         let asyncness = self.parse_asyncness(case);
2242
2243         let unsafe_start_sp = self.token.span;
2244         let unsafety = self.parse_unsafety(case);
2245
2246         let ext_start_sp = self.token.span;
2247         let ext = self.parse_extern(case);
2248
2249         if let Async::Yes { span, .. } = asyncness {
2250             if span.is_rust_2015() {
2251                 self.sess.emit_err(AsyncFnIn2015 { span, help: HelpUseLatestEdition::new() });
2252             }
2253         }
2254
2255         if !self.eat_keyword_case(kw::Fn, case) {
2256             // It is possible for `expect_one_of` to recover given the contents of
2257             // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2258             // account for this.
2259             match self.expect_one_of(&[], &[]) {
2260                 Ok(true) => {}
2261                 Ok(false) => unreachable!(),
2262                 Err(mut err) => {
2263                     // Qualifier keywords ordering check
2264                     enum WrongKw {
2265                         Duplicated(Span),
2266                         Misplaced(Span),
2267                     }
2268
2269                     // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2270                     // that the keyword is already present and the second instance should be removed.
2271                     let wrong_kw = if self.check_keyword(kw::Const) {
2272                         match constness {
2273                             Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2274                             Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2275                         }
2276                     } else if self.check_keyword(kw::Async) {
2277                         match asyncness {
2278                             Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2279                             Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2280                         }
2281                     } else if self.check_keyword(kw::Unsafe) {
2282                         match unsafety {
2283                             Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2284                             Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2285                         }
2286                     } else {
2287                         None
2288                     };
2289
2290                     // The keyword is already present, suggest removal of the second instance
2291                     if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2292                         let original_kw = self
2293                             .span_to_snippet(original_sp)
2294                             .expect("Span extracted directly from keyword should always work");
2295
2296                         err.span_suggestion(
2297                             self.token.uninterpolated_span(),
2298                             &format!("`{original_kw}` already used earlier, remove this one"),
2299                             "",
2300                             Applicability::MachineApplicable,
2301                         )
2302                         .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2303                     }
2304                     // The keyword has not been seen yet, suggest correct placement in the function front matter
2305                     else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2306                         let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2307                         if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2308                             let misplaced_qual_sp = self.token.uninterpolated_span();
2309                             let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2310
2311                             err.span_suggestion(
2312                                     correct_pos_sp.to(misplaced_qual_sp),
2313                                     &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2314                                     format!("{misplaced_qual} {current_qual}"),
2315                                     Applicability::MachineApplicable,
2316                                 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2317                         }
2318                     }
2319                     // Recover incorrect visibility order such as `async pub`
2320                     else if self.check_keyword(kw::Pub) {
2321                         let sp = sp_start.to(self.prev_token.span);
2322                         if let Ok(snippet) = self.span_to_snippet(sp) {
2323                             let current_vis = match self.parse_visibility(FollowedByType::No) {
2324                                 Ok(v) => v,
2325                                 Err(d) => {
2326                                     d.cancel();
2327                                     return Err(err);
2328                                 }
2329                             };
2330                             let vs = pprust::vis_to_string(&current_vis);
2331                             let vs = vs.trim_end();
2332
2333                             // There was no explicit visibility
2334                             if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2335                                 err.span_suggestion(
2336                                     sp_start.to(self.prev_token.span),
2337                                     &format!("visibility `{vs}` must come before `{snippet}`"),
2338                                     format!("{vs} {snippet}"),
2339                                     Applicability::MachineApplicable,
2340                                 );
2341                             }
2342                             // There was an explicit visibility
2343                             else {
2344                                 err.span_suggestion(
2345                                     current_vis.span,
2346                                     "there is already a visibility modifier, remove one",
2347                                     "",
2348                                     Applicability::MachineApplicable,
2349                                 )
2350                                 .span_note(orig_vis.span, "explicit visibility first seen here");
2351                             }
2352                         }
2353                     }
2354                     return Err(err);
2355                 }
2356             }
2357         }
2358
2359         Ok(FnHeader { constness, unsafety, asyncness, ext })
2360     }
2361
2362     /// Parses the parameter list and result type of a function declaration.
2363     pub(super) fn parse_fn_decl(
2364         &mut self,
2365         req_name: ReqName,
2366         ret_allow_plus: AllowPlus,
2367         recover_return_sign: RecoverReturnSign,
2368     ) -> PResult<'a, P<FnDecl>> {
2369         Ok(P(FnDecl {
2370             inputs: self.parse_fn_params(req_name)?,
2371             output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2372         }))
2373     }
2374
2375     /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2376     pub(super) fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2377         let mut first_param = true;
2378         // Parse the arguments, starting out with `self` being allowed...
2379         let (mut params, _) = self.parse_paren_comma_seq(|p| {
2380             p.recover_diff_marker();
2381             let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2382                 e.emit();
2383                 let lo = p.prev_token.span;
2384                 // Skip every token until next possible arg or end.
2385                 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2386                 // Create a placeholder argument for proper arg count (issue #34264).
2387                 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2388             });
2389             // ...now that we've parsed the first argument, `self` is no longer allowed.
2390             first_param = false;
2391             param
2392         })?;
2393         // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2394         self.deduplicate_recovered_params_names(&mut params);
2395         Ok(params)
2396     }
2397
2398     /// Parses a single function parameter.
2399     ///
2400     /// - `self` is syntactically allowed when `first_param` holds.
2401     fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2402         let lo = self.token.span;
2403         let attrs = self.parse_outer_attributes()?;
2404         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2405             // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2406             if let Some(mut param) = this.parse_self_param()? {
2407                 param.attrs = attrs;
2408                 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2409                 return Ok((res?, TrailingToken::None));
2410             }
2411
2412             let is_name_required = match this.token.kind {
2413                 token::DotDotDot => false,
2414                 _ => req_name(this.token.span.edition()),
2415             };
2416             let (pat, ty) = if is_name_required || this.is_named_param() {
2417                 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2418                 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2419                 if !colon {
2420                     let mut err = this.unexpected::<()>().unwrap_err();
2421                     return if let Some(ident) =
2422                         this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2423                     {
2424                         err.emit();
2425                         Ok((dummy_arg(ident), TrailingToken::None))
2426                     } else {
2427                         Err(err)
2428                     };
2429                 }
2430
2431                 this.eat_incorrect_doc_comment_for_param_type();
2432                 (pat, this.parse_ty_for_param()?)
2433             } else {
2434                 debug!("parse_param_general ident_to_pat");
2435                 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2436                 this.eat_incorrect_doc_comment_for_param_type();
2437                 let mut ty = this.parse_ty_for_param();
2438                 if ty.is_ok()
2439                     && this.token != token::Comma
2440                     && this.token != token::CloseDelim(Delimiter::Parenthesis)
2441                 {
2442                     // This wasn't actually a type, but a pattern looking like a type,
2443                     // so we are going to rollback and re-parse for recovery.
2444                     ty = this.unexpected();
2445                 }
2446                 match ty {
2447                     Ok(ty) => {
2448                         let ident = Ident::new(kw::Empty, this.prev_token.span);
2449                         let bm = BindingAnnotation::NONE;
2450                         let pat = this.mk_pat_ident(ty.span, bm, ident);
2451                         (pat, ty)
2452                     }
2453                     // If this is a C-variadic argument and we hit an error, return the error.
2454                     Err(err) if this.token == token::DotDotDot => return Err(err),
2455                     // Recover from attempting to parse the argument as a type without pattern.
2456                     Err(err) => {
2457                         err.cancel();
2458                         this.restore_snapshot(parser_snapshot_before_ty);
2459                         this.recover_arg_parse()?
2460                     }
2461                 }
2462             };
2463
2464             let span = lo.to(this.prev_token.span);
2465
2466             Ok((
2467                 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2468                 TrailingToken::None,
2469             ))
2470         })
2471     }
2472
2473     /// Returns the parsed optional self parameter and whether a self shortcut was used.
2474     fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2475         // Extract an identifier *after* having confirmed that the token is one.
2476         let expect_self_ident = |this: &mut Self| match this.token.ident() {
2477             Some((ident, false)) => {
2478                 this.bump();
2479                 ident
2480             }
2481             _ => unreachable!(),
2482         };
2483         // Is `self` `n` tokens ahead?
2484         let is_isolated_self = |this: &Self, n| {
2485             this.is_keyword_ahead(n, &[kw::SelfLower])
2486                 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2487         };
2488         // Is `mut self` `n` tokens ahead?
2489         let is_isolated_mut_self =
2490             |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2491         // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2492         let parse_self_possibly_typed = |this: &mut Self, m| {
2493             let eself_ident = expect_self_ident(this);
2494             let eself_hi = this.prev_token.span;
2495             let eself = if this.eat(&token::Colon) {
2496                 SelfKind::Explicit(this.parse_ty()?, m)
2497             } else {
2498                 SelfKind::Value(m)
2499             };
2500             Ok((eself, eself_ident, eself_hi))
2501         };
2502         // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2503         let recover_self_ptr = |this: &mut Self| {
2504             self.sess.emit_err(SelfArgumentPointer { span: this.token.span });
2505
2506             Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2507         };
2508
2509         // Parse optional `self` parameter of a method.
2510         // Only a limited set of initial token sequences is considered `self` parameters; anything
2511         // else is parsed as a normal function parameter list, so some lookahead is required.
2512         let eself_lo = self.token.span;
2513         let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2514             token::BinOp(token::And) => {
2515                 let eself = if is_isolated_self(self, 1) {
2516                     // `&self`
2517                     self.bump();
2518                     SelfKind::Region(None, Mutability::Not)
2519                 } else if is_isolated_mut_self(self, 1) {
2520                     // `&mut self`
2521                     self.bump();
2522                     self.bump();
2523                     SelfKind::Region(None, Mutability::Mut)
2524                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2525                     // `&'lt self`
2526                     self.bump();
2527                     let lt = self.expect_lifetime();
2528                     SelfKind::Region(Some(lt), Mutability::Not)
2529                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2530                     // `&'lt mut self`
2531                     self.bump();
2532                     let lt = self.expect_lifetime();
2533                     self.bump();
2534                     SelfKind::Region(Some(lt), Mutability::Mut)
2535                 } else {
2536                     // `&not_self`
2537                     return Ok(None);
2538                 };
2539                 (eself, expect_self_ident(self), self.prev_token.span)
2540             }
2541             // `*self`
2542             token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2543                 self.bump();
2544                 recover_self_ptr(self)?
2545             }
2546             // `*mut self` and `*const self`
2547             token::BinOp(token::Star)
2548                 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2549             {
2550                 self.bump();
2551                 self.bump();
2552                 recover_self_ptr(self)?
2553             }
2554             // `self` and `self: TYPE`
2555             token::Ident(..) if is_isolated_self(self, 0) => {
2556                 parse_self_possibly_typed(self, Mutability::Not)?
2557             }
2558             // `mut self` and `mut self: TYPE`
2559             token::Ident(..) if is_isolated_mut_self(self, 0) => {
2560                 self.bump();
2561                 parse_self_possibly_typed(self, Mutability::Mut)?
2562             }
2563             _ => return Ok(None),
2564         };
2565
2566         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2567         Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2568     }
2569
2570     fn is_named_param(&self) -> bool {
2571         let offset = match &self.token.kind {
2572             token::Interpolated(nt) => match **nt {
2573                 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2574                 _ => 0,
2575             },
2576             token::BinOp(token::And) | token::AndAnd => 1,
2577             _ if self.token.is_keyword(kw::Mut) => 1,
2578             _ => 0,
2579         };
2580
2581         self.look_ahead(offset, |t| t.is_ident())
2582             && self.look_ahead(offset + 1, |t| t == &token::Colon)
2583     }
2584
2585     fn recover_self_param(&mut self) -> bool {
2586         match self
2587             .parse_outer_attributes()
2588             .and_then(|_| self.parse_self_param())
2589             .map_err(|e| e.cancel())
2590         {
2591             Ok(Some(_)) => true,
2592             _ => false,
2593         }
2594     }
2595 }
2596
2597 enum IsMacroRulesItem {
2598     Yes { has_bang: bool },
2599     No,
2600 }