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