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