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