]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/item.rs
Auto merge of #95977 - FabianWolff:issue-92790-dead-tuple, r=estebank
[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         if self.token.is_keyword(kw::Struct) {
1220             let mut err = self.struct_span_err(
1221                 self.prev_token.span.to(self.token.span),
1222                 "`enum` and `struct` are mutually exclusive",
1223             );
1224             err.span_suggestion(
1225                 self.prev_token.span.to(self.token.span),
1226                 "replace `enum struct` with",
1227                 "enum",
1228                 Applicability::MachineApplicable,
1229             );
1230             if self.look_ahead(1, |t| t.is_ident()) {
1231                 self.bump();
1232                 err.emit();
1233             } else {
1234                 return Err(err);
1235             }
1236         }
1237
1238         let id = self.parse_ident()?;
1239         let mut generics = self.parse_generics()?;
1240         generics.where_clause = self.parse_where_clause()?;
1241
1242         let (variants, _) = self
1243             .parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant())
1244             .map_err(|e| {
1245                 self.recover_stmt();
1246                 e
1247             })?;
1248
1249         let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1250         Ok((id, ItemKind::Enum(enum_definition, generics)))
1251     }
1252
1253     fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1254         let variant_attrs = self.parse_outer_attributes()?;
1255         self.collect_tokens_trailing_token(
1256             variant_attrs,
1257             ForceCollect::No,
1258             |this, variant_attrs| {
1259                 let vlo = this.token.span;
1260
1261                 let vis = this.parse_visibility(FollowedByType::No)?;
1262                 if !this.recover_nested_adt_item(kw::Enum)? {
1263                     return Ok((None, TrailingToken::None));
1264                 }
1265                 let ident = this.parse_field_ident("enum", vlo)?;
1266
1267                 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1268                     // Parse a struct variant.
1269                     let (fields, recovered) = this.parse_record_struct_body("struct", false)?;
1270                     VariantData::Struct(fields, recovered)
1271                 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1272                     VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1273                 } else {
1274                     VariantData::Unit(DUMMY_NODE_ID)
1275                 };
1276
1277                 let disr_expr =
1278                     if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1279
1280                 let vr = ast::Variant {
1281                     ident,
1282                     vis,
1283                     id: DUMMY_NODE_ID,
1284                     attrs: variant_attrs.into(),
1285                     data: struct_def,
1286                     disr_expr,
1287                     span: vlo.to(this.prev_token.span),
1288                     is_placeholder: false,
1289                 };
1290
1291                 Ok((Some(vr), TrailingToken::MaybeComma))
1292             },
1293         )
1294     }
1295
1296     /// Parses `struct Foo { ... }`.
1297     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1298         let class_name = self.parse_ident()?;
1299
1300         let mut generics = self.parse_generics()?;
1301
1302         // There is a special case worth noting here, as reported in issue #17904.
1303         // If we are parsing a tuple struct it is the case that the where clause
1304         // should follow the field list. Like so:
1305         //
1306         // struct Foo<T>(T) where T: Copy;
1307         //
1308         // If we are parsing a normal record-style struct it is the case
1309         // that the where clause comes before the body, and after the generics.
1310         // So if we look ahead and see a brace or a where-clause we begin
1311         // parsing a record style struct.
1312         //
1313         // Otherwise if we look ahead and see a paren we parse a tuple-style
1314         // struct.
1315
1316         let vdata = if self.token.is_keyword(kw::Where) {
1317             generics.where_clause = self.parse_where_clause()?;
1318             if self.eat(&token::Semi) {
1319                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1320                 VariantData::Unit(DUMMY_NODE_ID)
1321             } else {
1322                 // If we see: `struct Foo<T> where T: Copy { ... }`
1323                 let (fields, recovered) =
1324                     self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1325                 VariantData::Struct(fields, recovered)
1326             }
1327         // No `where` so: `struct Foo<T>;`
1328         } else if self.eat(&token::Semi) {
1329             VariantData::Unit(DUMMY_NODE_ID)
1330         // Record-style struct definition
1331         } else if self.token == token::OpenDelim(Delimiter::Brace) {
1332             let (fields, recovered) =
1333                 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1334             VariantData::Struct(fields, recovered)
1335         // Tuple-style struct definition with optional where-clause.
1336         } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1337             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1338             generics.where_clause = self.parse_where_clause()?;
1339             self.expect_semi()?;
1340             body
1341         } else {
1342             let token_str = super::token_descr(&self.token);
1343             let msg = &format!(
1344                 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1345             );
1346             let mut err = self.struct_span_err(self.token.span, msg);
1347             err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1348             return Err(err);
1349         };
1350
1351         Ok((class_name, ItemKind::Struct(vdata, generics)))
1352     }
1353
1354     /// Parses `union Foo { ... }`.
1355     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1356         let class_name = self.parse_ident()?;
1357
1358         let mut generics = self.parse_generics()?;
1359
1360         let vdata = if self.token.is_keyword(kw::Where) {
1361             generics.where_clause = self.parse_where_clause()?;
1362             let (fields, recovered) =
1363                 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1364             VariantData::Struct(fields, recovered)
1365         } else if self.token == token::OpenDelim(Delimiter::Brace) {
1366             let (fields, recovered) =
1367                 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1368             VariantData::Struct(fields, recovered)
1369         } else {
1370             let token_str = super::token_descr(&self.token);
1371             let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1372             let mut err = self.struct_span_err(self.token.span, msg);
1373             err.span_label(self.token.span, "expected `where` or `{` after union name");
1374             return Err(err);
1375         };
1376
1377         Ok((class_name, ItemKind::Union(vdata, generics)))
1378     }
1379
1380     fn parse_record_struct_body(
1381         &mut self,
1382         adt_ty: &str,
1383         parsed_where: bool,
1384     ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1385         let mut fields = Vec::new();
1386         let mut recovered = false;
1387         if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1388             while self.token != token::CloseDelim(Delimiter::Brace) {
1389                 let field = self.parse_field_def(adt_ty).map_err(|e| {
1390                     self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1391                     recovered = true;
1392                     e
1393                 });
1394                 match field {
1395                     Ok(field) => fields.push(field),
1396                     Err(mut err) => {
1397                         err.emit();
1398                         break;
1399                     }
1400                 }
1401             }
1402             self.eat(&token::CloseDelim(Delimiter::Brace));
1403         } else {
1404             let token_str = super::token_descr(&self.token);
1405             let msg = &format!(
1406                 "expected {}`{{` after struct name, found {}",
1407                 if parsed_where { "" } else { "`where`, or " },
1408                 token_str
1409             );
1410             let mut err = self.struct_span_err(self.token.span, msg);
1411             err.span_label(
1412                 self.token.span,
1413                 format!(
1414                     "expected {}`{{` after struct name",
1415                     if parsed_where { "" } else { "`where`, or " }
1416                 ),
1417             );
1418             return Err(err);
1419         }
1420
1421         Ok((fields, recovered))
1422     }
1423
1424     fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1425         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1426         // Unit like structs are handled in parse_item_struct function
1427         self.parse_paren_comma_seq(|p| {
1428             let attrs = p.parse_outer_attributes()?;
1429             p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1430                 let lo = p.token.span;
1431                 let vis = p.parse_visibility(FollowedByType::Yes)?;
1432                 let ty = p.parse_ty()?;
1433
1434                 Ok((
1435                     FieldDef {
1436                         span: lo.to(ty.span),
1437                         vis,
1438                         ident: None,
1439                         id: DUMMY_NODE_ID,
1440                         ty,
1441                         attrs: attrs.into(),
1442                         is_placeholder: false,
1443                     },
1444                     TrailingToken::MaybeComma,
1445                 ))
1446             })
1447         })
1448         .map(|(r, _)| r)
1449     }
1450
1451     /// Parses an element of a struct declaration.
1452     fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1453         let attrs = self.parse_outer_attributes()?;
1454         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1455             let lo = this.token.span;
1456             let vis = this.parse_visibility(FollowedByType::No)?;
1457             Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1458         })
1459     }
1460
1461     /// Parses a structure field declaration.
1462     fn parse_single_struct_field(
1463         &mut self,
1464         adt_ty: &str,
1465         lo: Span,
1466         vis: Visibility,
1467         attrs: Vec<Attribute>,
1468     ) -> PResult<'a, FieldDef> {
1469         let mut seen_comma: bool = false;
1470         let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1471         if self.token == token::Comma {
1472             seen_comma = true;
1473         }
1474         match self.token.kind {
1475             token::Comma => {
1476                 self.bump();
1477             }
1478             token::CloseDelim(Delimiter::Brace) => {}
1479             token::DocComment(..) => {
1480                 let previous_span = self.prev_token.span;
1481                 let mut err = self.span_err(self.token.span, Error::UselessDocComment);
1482                 self.bump(); // consume the doc comment
1483                 let comma_after_doc_seen = self.eat(&token::Comma);
1484                 // `seen_comma` is always false, because we are inside doc block
1485                 // condition is here to make code more readable
1486                 if !seen_comma && comma_after_doc_seen {
1487                     seen_comma = true;
1488                 }
1489                 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1490                     err.emit();
1491                 } else {
1492                     if !seen_comma {
1493                         let sp = self.sess.source_map().next_point(previous_span);
1494                         err.span_suggestion(
1495                             sp,
1496                             "missing comma here",
1497                             ",",
1498                             Applicability::MachineApplicable,
1499                         );
1500                     }
1501                     return Err(err);
1502                 }
1503             }
1504             _ => {
1505                 let sp = self.prev_token.span.shrink_to_hi();
1506                 let mut err = self.struct_span_err(
1507                     sp,
1508                     &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1509                 );
1510
1511                 // Try to recover extra trailing angle brackets
1512                 let mut recovered = false;
1513                 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1514                     if let Some(last_segment) = segments.last() {
1515                         recovered = self.check_trailing_angle_brackets(
1516                             last_segment,
1517                             &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1518                         );
1519                         if recovered {
1520                             // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1521                             // after the comma
1522                             self.eat(&token::Comma);
1523                             // `check_trailing_angle_brackets` already emitted a nicer error
1524                             // NOTE(eddyb) this was `.cancel()`, but `err`
1525                             // gets returned, so we can't fully defuse it.
1526                             err.delay_as_bug();
1527                         }
1528                     }
1529                 }
1530
1531                 if self.token.is_ident() {
1532                     // This is likely another field; emit the diagnostic and keep going
1533                     err.span_suggestion(
1534                         sp,
1535                         "try adding a comma",
1536                         ",",
1537                         Applicability::MachineApplicable,
1538                     );
1539                     err.emit();
1540                     recovered = true;
1541                 }
1542
1543                 if recovered {
1544                     // Make sure an error was emitted (either by recovering an angle bracket,
1545                     // or by finding an identifier as the next token), since we're
1546                     // going to continue parsing
1547                     assert!(self.sess.span_diagnostic.has_errors().is_some());
1548                 } else {
1549                     return Err(err);
1550                 }
1551             }
1552         }
1553         Ok(a_var)
1554     }
1555
1556     fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1557         if let Err(mut err) = self.expect(&token::Colon) {
1558             let sm = self.sess.source_map();
1559             let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1560             let semi_typo = self.token.kind == token::Semi
1561                 && self.look_ahead(1, |t| {
1562                     t.is_path_start()
1563                     // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1564                     // when there's no type and `;` was used instead of a comma.
1565                     && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1566                         (Ok(l), Ok(r)) => l.line == r.line,
1567                         _ => true,
1568                     }
1569                 });
1570             if eq_typo || semi_typo {
1571                 self.bump();
1572                 // Gracefully handle small typos.
1573                 err.span_suggestion_short(
1574                     self.prev_token.span,
1575                     "field names and their types are separated with `:`",
1576                     ":",
1577                     Applicability::MachineApplicable,
1578                 );
1579                 err.emit();
1580             } else {
1581                 return Err(err);
1582             }
1583         }
1584         Ok(())
1585     }
1586
1587     /// Parses a structure field.
1588     fn parse_name_and_ty(
1589         &mut self,
1590         adt_ty: &str,
1591         lo: Span,
1592         vis: Visibility,
1593         attrs: Vec<Attribute>,
1594     ) -> PResult<'a, FieldDef> {
1595         let name = self.parse_field_ident(adt_ty, lo)?;
1596         self.expect_field_ty_separator()?;
1597         let ty = self.parse_ty()?;
1598         if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1599             self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1600                 .span_suggestion_verbose(
1601                     self.token.span,
1602                     "write a path separator here",
1603                     "::",
1604                     Applicability::MaybeIncorrect,
1605                 )
1606                 .emit();
1607         }
1608         if self.token.kind == token::Eq {
1609             self.bump();
1610             let const_expr = self.parse_anon_const_expr()?;
1611             let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1612             self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1613                 .span_suggestion(
1614                     sp,
1615                     "remove this unsupported default value",
1616                     "",
1617                     Applicability::MachineApplicable,
1618                 )
1619                 .emit();
1620         }
1621         Ok(FieldDef {
1622             span: lo.to(self.prev_token.span),
1623             ident: Some(name),
1624             vis,
1625             id: DUMMY_NODE_ID,
1626             ty,
1627             attrs: attrs.into(),
1628             is_placeholder: false,
1629         })
1630     }
1631
1632     /// Parses a field identifier. Specialized version of `parse_ident_common`
1633     /// for better diagnostics and suggestions.
1634     fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1635         let (ident, is_raw) = self.ident_or_err()?;
1636         if !is_raw && ident.is_reserved() {
1637             let err = if self.check_fn_front_matter(false) {
1638                 let inherited_vis = Visibility {
1639                     span: rustc_span::DUMMY_SP,
1640                     kind: VisibilityKind::Inherited,
1641                     tokens: None,
1642                 };
1643                 // We use `parse_fn` to get a span for the function
1644                 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1645                 if let Err(mut db) =
1646                     self.parse_fn(&mut Vec::new(), fn_parse_mode, lo, &inherited_vis)
1647                 {
1648                     db.delay_as_bug();
1649                 }
1650                 let mut err = self.struct_span_err(
1651                     lo.to(self.prev_token.span),
1652                     &format!("functions are not allowed in {adt_ty} definitions"),
1653                 );
1654                 err.help("unlike in C++, Java, and C#, functions are declared in `impl` blocks");
1655                 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1656                 err
1657             } else {
1658                 self.expected_ident_found()
1659             };
1660             return Err(err);
1661         }
1662         self.bump();
1663         Ok(ident)
1664     }
1665
1666     /// Parses a declarative macro 2.0 definition.
1667     /// The `macro` keyword has already been parsed.
1668     /// ```ebnf
1669     /// MacBody = "{" TOKEN_STREAM "}" ;
1670     /// MacParams = "(" TOKEN_STREAM ")" ;
1671     /// DeclMac = "macro" Ident MacParams? MacBody ;
1672     /// ```
1673     fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1674         let ident = self.parse_ident()?;
1675         let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1676             self.parse_mac_args()? // `MacBody`
1677         } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1678             let params = self.parse_token_tree(); // `MacParams`
1679             let pspan = params.span();
1680             if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1681                 return self.unexpected();
1682             }
1683             let body = self.parse_token_tree(); // `MacBody`
1684             // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1685             let bspan = body.span();
1686             let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1687             let tokens = TokenStream::new(vec![params, arrow, body]);
1688             let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1689             P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1690         } else {
1691             return self.unexpected();
1692         };
1693
1694         self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1695         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1696     }
1697
1698     /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1699     fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1700         if self.check_keyword(kw::MacroRules) {
1701             let macro_rules_span = self.token.span;
1702
1703             if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1704                 return IsMacroRulesItem::Yes { has_bang: true };
1705             } else if self.look_ahead(1, |t| (t.is_ident())) {
1706                 // macro_rules foo
1707                 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1708                     .span_suggestion(
1709                         macro_rules_span,
1710                         "add a `!`",
1711                         "macro_rules!",
1712                         Applicability::MachineApplicable,
1713                     )
1714                     .emit();
1715
1716                 return IsMacroRulesItem::Yes { has_bang: false };
1717             }
1718         }
1719
1720         IsMacroRulesItem::No
1721     }
1722
1723     /// Parses a `macro_rules! foo { ... }` declarative macro.
1724     fn parse_item_macro_rules(
1725         &mut self,
1726         vis: &Visibility,
1727         has_bang: bool,
1728     ) -> PResult<'a, ItemInfo> {
1729         self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1730
1731         if has_bang {
1732             self.expect(&token::Not)?; // `!`
1733         }
1734         let ident = self.parse_ident()?;
1735
1736         if self.eat(&token::Not) {
1737             // Handle macro_rules! foo!
1738             let span = self.prev_token.span;
1739             self.struct_span_err(span, "macro names aren't followed by a `!`")
1740                 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1741                 .emit();
1742         }
1743
1744         let body = self.parse_mac_args()?;
1745         self.eat_semi_for_macro_if_needed(&body);
1746         self.complain_if_pub_macro(vis, true);
1747
1748         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1749     }
1750
1751     /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1752     /// If that's not the case, emit an error.
1753     fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1754         if let VisibilityKind::Inherited = vis.kind {
1755             return;
1756         }
1757
1758         let vstr = pprust::vis_to_string(vis);
1759         let vstr = vstr.trim_end();
1760         if macro_rules {
1761             let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1762             self.struct_span_err(vis.span, &msg)
1763                 .span_suggestion(
1764                     vis.span,
1765                     "try exporting the macro",
1766                     "#[macro_export]",
1767                     Applicability::MaybeIncorrect, // speculative
1768                 )
1769                 .emit();
1770         } else {
1771             self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1772                 .span_suggestion(
1773                     vis.span,
1774                     "remove the visibility",
1775                     "",
1776                     Applicability::MachineApplicable,
1777                 )
1778                 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1779                 .emit();
1780         }
1781     }
1782
1783     fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1784         if args.need_semicolon() && !self.eat(&token::Semi) {
1785             self.report_invalid_macro_expansion_item(args);
1786         }
1787     }
1788
1789     fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1790         let span = args.span().expect("undelimited macro call");
1791         let mut err = self.struct_span_err(
1792             span,
1793             "macros that expand to items must be delimited with braces or followed by a semicolon",
1794         );
1795         // FIXME: This will make us not emit the help even for declarative
1796         // macros within the same crate (that we can fix), which is sad.
1797         if !span.from_expansion() {
1798             if self.unclosed_delims.is_empty() {
1799                 let DelimSpan { open, close } = match args {
1800                     MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1801                     MacArgs::Delimited(dspan, ..) => *dspan,
1802                 };
1803                 err.multipart_suggestion(
1804                     "change the delimiters to curly braces",
1805                     vec![(open, "{".to_string()), (close, '}'.to_string())],
1806                     Applicability::MaybeIncorrect,
1807                 );
1808             } else {
1809                 err.span_suggestion(
1810                     span,
1811                     "change the delimiters to curly braces",
1812                     " { /* items */ }",
1813                     Applicability::HasPlaceholders,
1814                 );
1815             }
1816             err.span_suggestion(
1817                 span.shrink_to_hi(),
1818                 "add a semicolon",
1819                 ';',
1820                 Applicability::MaybeIncorrect,
1821             );
1822         }
1823         err.emit();
1824     }
1825
1826     /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1827     /// it is, we try to parse the item and report error about nested types.
1828     fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1829         if (self.token.is_keyword(kw::Enum)
1830             || self.token.is_keyword(kw::Struct)
1831             || self.token.is_keyword(kw::Union))
1832             && self.look_ahead(1, |t| t.is_ident())
1833         {
1834             let kw_token = self.token.clone();
1835             let kw_str = pprust::token_to_string(&kw_token);
1836             let item = self.parse_item(ForceCollect::No)?;
1837
1838             self.struct_span_err(
1839                 kw_token.span,
1840                 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
1841             )
1842             .span_suggestion(
1843                 item.unwrap().span,
1844                 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
1845                 "",
1846                 Applicability::MaybeIncorrect,
1847             )
1848             .emit();
1849             // We successfully parsed the item but we must inform the caller about nested problem.
1850             return Ok(false);
1851         }
1852         Ok(true)
1853     }
1854 }
1855
1856 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1857 ///
1858 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1859 ///
1860 /// This function pointer accepts an edition, because in edition 2015, trait declarations
1861 /// were allowed to omit parameter names. In 2018, they became required.
1862 type ReqName = fn(Edition) -> bool;
1863
1864 /// Parsing configuration for functions.
1865 ///
1866 /// The syntax of function items is slightly different within trait definitions,
1867 /// impl blocks, and modules. It is still parsed using the same code, just with
1868 /// different flags set, so that even when the input is wrong and produces a parse
1869 /// error, it still gets into the AST and the rest of the parser and
1870 /// type checker can run.
1871 #[derive(Clone, Copy)]
1872 pub(crate) struct FnParseMode {
1873     /// A function pointer that decides if, per-parameter `p`, `p` must have a
1874     /// pattern or just a type. This field affects parsing of the parameters list.
1875     ///
1876     /// ```text
1877     /// fn foo(alef: A) -> X { X::new() }
1878     ///        -----^^ affects parsing this part of the function signature
1879     ///        |
1880     ///        if req_name returns false, then this name is optional
1881     ///
1882     /// fn bar(A) -> X;
1883     ///        ^
1884     ///        |
1885     ///        if req_name returns true, this is an error
1886     /// ```
1887     ///
1888     /// Calling this function pointer should only return false if:
1889     ///
1890     ///   * The item is being parsed inside of a trait definition.
1891     ///     Within an impl block or a module, it should always evaluate
1892     ///     to true.
1893     ///   * The span is from Edition 2015. In particular, you can get a
1894     ///     2015 span inside a 2021 crate using macros.
1895     pub req_name: ReqName,
1896     /// If this flag is set to `true`, then plain, semicolon-terminated function
1897     /// prototypes are not allowed here.
1898     ///
1899     /// ```text
1900     /// fn foo(alef: A) -> X { X::new() }
1901     ///                      ^^^^^^^^^^^^
1902     ///                      |
1903     ///                      this is always allowed
1904     ///
1905     /// fn bar(alef: A, bet: B) -> X;
1906     ///                             ^
1907     ///                             |
1908     ///                             if req_body is set to true, this is an error
1909     /// ```
1910     ///
1911     /// This field should only be set to false if the item is inside of a trait
1912     /// definition or extern block. Within an impl block or a module, it should
1913     /// always be set to true.
1914     pub req_body: bool,
1915 }
1916
1917 /// Parsing of functions and methods.
1918 impl<'a> Parser<'a> {
1919     /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1920     fn parse_fn(
1921         &mut self,
1922         attrs: &mut Vec<Attribute>,
1923         fn_parse_mode: FnParseMode,
1924         sig_lo: Span,
1925         vis: &Visibility,
1926     ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1927         let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
1928         let ident = self.parse_ident()?; // `foo`
1929         let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1930         let decl =
1931             self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1932         generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1933
1934         let mut sig_hi = self.prev_token.span;
1935         let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
1936         let fn_sig_span = sig_lo.to(sig_hi);
1937         Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1938     }
1939
1940     /// Parse the "body" of a function.
1941     /// This can either be `;` when there's no body,
1942     /// or e.g. a block when the function is a provided one.
1943     fn parse_fn_body(
1944         &mut self,
1945         attrs: &mut Vec<Attribute>,
1946         ident: &Ident,
1947         sig_hi: &mut Span,
1948         req_body: bool,
1949     ) -> PResult<'a, Option<P<Block>>> {
1950         let has_semi = if req_body {
1951             self.token.kind == TokenKind::Semi
1952         } else {
1953             // Only include `;` in list of expected tokens if body is not required
1954             self.check(&TokenKind::Semi)
1955         };
1956         let (inner_attrs, body) = if has_semi {
1957             // Include the trailing semicolon in the span of the signature
1958             self.expect_semi()?;
1959             *sig_hi = self.prev_token.span;
1960             (Vec::new(), None)
1961         } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
1962             self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1963         } else if self.token.kind == token::Eq {
1964             // Recover `fn foo() = $expr;`.
1965             self.bump(); // `=`
1966             let eq_sp = self.prev_token.span;
1967             let _ = self.parse_expr()?;
1968             self.expect_semi()?; // `;`
1969             let span = eq_sp.to(self.prev_token.span);
1970             self.struct_span_err(span, "function body cannot be `= expression;`")
1971                 .multipart_suggestion(
1972                     "surround the expression with `{` and `}` instead of `=` and `;`",
1973                     vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1974                     Applicability::MachineApplicable,
1975                 )
1976                 .emit();
1977             (Vec::new(), Some(self.mk_block_err(span)))
1978         } else {
1979             let expected = if req_body {
1980                 &[token::OpenDelim(Delimiter::Brace)][..]
1981             } else {
1982                 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
1983             };
1984             if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
1985                 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
1986                     // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1987                     // the AST for typechecking.
1988                     err.span_label(ident.span, "while parsing this `fn`");
1989                     err.emit();
1990                 } else {
1991                     return Err(err);
1992                 }
1993             }
1994             (Vec::new(), None)
1995         };
1996         attrs.extend(inner_attrs);
1997         Ok(body)
1998     }
1999
2000     /// Is the current token the start of an `FnHeader` / not a valid parse?
2001     ///
2002     /// `check_pub` adds additional `pub` to the checks in case users place it
2003     /// wrongly, can be used to ensure `pub` never comes after `default`.
2004     pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
2005         // We use an over-approximation here.
2006         // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2007         // `pub` is added in case users got confused with the ordering like `async pub fn`,
2008         // only if it wasn't preceded by `default` as `default pub` is invalid.
2009         let quals: &[Symbol] = if check_pub {
2010             &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2011         } else {
2012             &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2013         };
2014         self.check_keyword(kw::Fn) // Definitely an `fn`.
2015             // `$qual fn` or `$qual $qual`:
2016             || quals.iter().any(|&kw| self.check_keyword(kw))
2017                 && self.look_ahead(1, |t| {
2018                     // `$qual fn`, e.g. `const fn` or `async fn`.
2019                     t.is_keyword(kw::Fn)
2020                     // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2021                     || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
2022                         // Rule out 2015 `const async: T = val`.
2023                         && i.is_reserved()
2024                         // Rule out unsafe extern block.
2025                         && !self.is_unsafe_foreign_mod())
2026                 })
2027             // `extern ABI fn`
2028             || self.check_keyword(kw::Extern)
2029                 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2030                 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
2031     }
2032
2033     /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2034     /// up to and including the `fn` keyword. The formal grammar is:
2035     ///
2036     /// ```text
2037     /// Extern = "extern" StringLit? ;
2038     /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2039     /// FnFrontMatter = FnQual "fn" ;
2040     /// ```
2041     ///
2042     /// `vis` represents the visibility that was already parsed, if any. Use
2043     /// `Visibility::Inherited` when no visibility is known.
2044     pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2045         let sp_start = self.token.span;
2046         let constness = self.parse_constness();
2047
2048         let async_start_sp = self.token.span;
2049         let asyncness = self.parse_asyncness();
2050
2051         let unsafe_start_sp = self.token.span;
2052         let unsafety = self.parse_unsafety();
2053
2054         let ext_start_sp = self.token.span;
2055         let ext = self.parse_extern();
2056
2057         if let Async::Yes { span, .. } = asyncness {
2058             self.ban_async_in_2015(span);
2059         }
2060
2061         if !self.eat_keyword(kw::Fn) {
2062             // It is possible for `expect_one_of` to recover given the contents of
2063             // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2064             // account for this.
2065             match self.expect_one_of(&[], &[]) {
2066                 Ok(true) => {}
2067                 Ok(false) => unreachable!(),
2068                 Err(mut err) => {
2069                     // Qualifier keywords ordering check
2070                     enum WrongKw {
2071                         Duplicated(Span),
2072                         Misplaced(Span),
2073                     }
2074
2075                     // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2076                     // that the keyword is already present and the second instance should be removed.
2077                     let wrong_kw = if self.check_keyword(kw::Const) {
2078                         match constness {
2079                             Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2080                             Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2081                         }
2082                     } else if self.check_keyword(kw::Async) {
2083                         match asyncness {
2084                             Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2085                             Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2086                         }
2087                     } else if self.check_keyword(kw::Unsafe) {
2088                         match unsafety {
2089                             Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2090                             Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2091                         }
2092                     } else {
2093                         None
2094                     };
2095
2096                     // The keyword is already present, suggest removal of the second instance
2097                     if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2098                         let original_kw = self
2099                             .span_to_snippet(original_sp)
2100                             .expect("Span extracted directly from keyword should always work");
2101
2102                         err.span_suggestion(
2103                             self.token.uninterpolated_span(),
2104                             &format!("`{original_kw}` already used earlier, remove this one"),
2105                             "",
2106                             Applicability::MachineApplicable,
2107                         )
2108                         .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2109                     }
2110                     // The keyword has not been seen yet, suggest correct placement in the function front matter
2111                     else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2112                         let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2113                         if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2114                             let misplaced_qual_sp = self.token.uninterpolated_span();
2115                             let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2116
2117                             err.span_suggestion(
2118                                     correct_pos_sp.to(misplaced_qual_sp),
2119                                     &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2120                                     format!("{misplaced_qual} {current_qual}"),
2121                                     Applicability::MachineApplicable,
2122                                 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2123                         }
2124                     }
2125                     // Recover incorrect visibility order such as `async pub`
2126                     else if self.check_keyword(kw::Pub) {
2127                         let sp = sp_start.to(self.prev_token.span);
2128                         if let Ok(snippet) = self.span_to_snippet(sp) {
2129                             let current_vis = match self.parse_visibility(FollowedByType::No) {
2130                                 Ok(v) => v,
2131                                 Err(d) => {
2132                                     d.cancel();
2133                                     return Err(err);
2134                                 }
2135                             };
2136                             let vs = pprust::vis_to_string(&current_vis);
2137                             let vs = vs.trim_end();
2138
2139                             // There was no explicit visibility
2140                             if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2141                                 err.span_suggestion(
2142                                     sp_start.to(self.prev_token.span),
2143                                     &format!("visibility `{vs}` must come before `{snippet}`"),
2144                                     format!("{vs} {snippet}"),
2145                                     Applicability::MachineApplicable,
2146                                 );
2147                             }
2148                             // There was an explicit visibility
2149                             else {
2150                                 err.span_suggestion(
2151                                     current_vis.span,
2152                                     "there is already a visibility modifier, remove one",
2153                                     "",
2154                                     Applicability::MachineApplicable,
2155                                 )
2156                                 .span_note(orig_vis.span, "explicit visibility first seen here");
2157                             }
2158                         }
2159                     }
2160                     return Err(err);
2161                 }
2162             }
2163         }
2164
2165         Ok(FnHeader { constness, unsafety, asyncness, ext })
2166     }
2167
2168     /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2169     fn ban_async_in_2015(&self, span: Span) {
2170         if span.rust_2015() {
2171             let diag = self.diagnostic();
2172             struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2173                 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2174                 .help_use_latest_edition()
2175                 .emit();
2176         }
2177     }
2178
2179     /// Parses the parameter list and result type of a function declaration.
2180     pub(super) fn parse_fn_decl(
2181         &mut self,
2182         req_name: ReqName,
2183         ret_allow_plus: AllowPlus,
2184         recover_return_sign: RecoverReturnSign,
2185     ) -> PResult<'a, P<FnDecl>> {
2186         Ok(P(FnDecl {
2187             inputs: self.parse_fn_params(req_name)?,
2188             output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2189         }))
2190     }
2191
2192     /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2193     fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2194         let mut first_param = true;
2195         // Parse the arguments, starting out with `self` being allowed...
2196         let (mut params, _) = self.parse_paren_comma_seq(|p| {
2197             let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2198                 e.emit();
2199                 let lo = p.prev_token.span;
2200                 // Skip every token until next possible arg or end.
2201                 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2202                 // Create a placeholder argument for proper arg count (issue #34264).
2203                 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2204             });
2205             // ...now that we've parsed the first argument, `self` is no longer allowed.
2206             first_param = false;
2207             param
2208         })?;
2209         // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2210         self.deduplicate_recovered_params_names(&mut params);
2211         Ok(params)
2212     }
2213
2214     /// Parses a single function parameter.
2215     ///
2216     /// - `self` is syntactically allowed when `first_param` holds.
2217     fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2218         let lo = self.token.span;
2219         let attrs = self.parse_outer_attributes()?;
2220         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2221             // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2222             if let Some(mut param) = this.parse_self_param()? {
2223                 param.attrs = attrs.into();
2224                 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2225                 return Ok((res?, TrailingToken::None));
2226             }
2227
2228             let is_name_required = match this.token.kind {
2229                 token::DotDotDot => false,
2230                 _ => req_name(this.token.span.edition()),
2231             };
2232             let (pat, ty) = if is_name_required || this.is_named_param() {
2233                 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2234
2235                 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2236                 if !colon {
2237                     let mut err = this.unexpected::<()>().unwrap_err();
2238                     return if let Some(ident) =
2239                         this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2240                     {
2241                         err.emit();
2242                         Ok((dummy_arg(ident), TrailingToken::None))
2243                     } else {
2244                         Err(err)
2245                     };
2246                 }
2247
2248                 this.eat_incorrect_doc_comment_for_param_type();
2249                 (pat, this.parse_ty_for_param()?)
2250             } else {
2251                 debug!("parse_param_general ident_to_pat");
2252                 let parser_snapshot_before_ty = this.clone();
2253                 this.eat_incorrect_doc_comment_for_param_type();
2254                 let mut ty = this.parse_ty_for_param();
2255                 if ty.is_ok()
2256                     && this.token != token::Comma
2257                     && this.token != token::CloseDelim(Delimiter::Parenthesis)
2258                 {
2259                     // This wasn't actually a type, but a pattern looking like a type,
2260                     // so we are going to rollback and re-parse for recovery.
2261                     ty = this.unexpected();
2262                 }
2263                 match ty {
2264                     Ok(ty) => {
2265                         let ident = Ident::new(kw::Empty, this.prev_token.span);
2266                         let bm = BindingMode::ByValue(Mutability::Not);
2267                         let pat = this.mk_pat_ident(ty.span, bm, ident);
2268                         (pat, ty)
2269                     }
2270                     // If this is a C-variadic argument and we hit an error, return the error.
2271                     Err(err) if this.token == token::DotDotDot => return Err(err),
2272                     // Recover from attempting to parse the argument as a type without pattern.
2273                     Err(err) => {
2274                         err.cancel();
2275                         *this = parser_snapshot_before_ty;
2276                         this.recover_arg_parse()?
2277                     }
2278                 }
2279             };
2280
2281             let span = lo.until(this.token.span);
2282
2283             Ok((
2284                 Param {
2285                     attrs: attrs.into(),
2286                     id: ast::DUMMY_NODE_ID,
2287                     is_placeholder: false,
2288                     pat,
2289                     span,
2290                     ty,
2291                 },
2292                 TrailingToken::None,
2293             ))
2294         })
2295     }
2296
2297     /// Returns the parsed optional self parameter and whether a self shortcut was used.
2298     fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2299         // Extract an identifier *after* having confirmed that the token is one.
2300         let expect_self_ident = |this: &mut Self| match this.token.ident() {
2301             Some((ident, false)) => {
2302                 this.bump();
2303                 ident
2304             }
2305             _ => unreachable!(),
2306         };
2307         // Is `self` `n` tokens ahead?
2308         let is_isolated_self = |this: &Self, n| {
2309             this.is_keyword_ahead(n, &[kw::SelfLower])
2310                 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2311         };
2312         // Is `mut self` `n` tokens ahead?
2313         let is_isolated_mut_self =
2314             |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2315         // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2316         let parse_self_possibly_typed = |this: &mut Self, m| {
2317             let eself_ident = expect_self_ident(this);
2318             let eself_hi = this.prev_token.span;
2319             let eself = if this.eat(&token::Colon) {
2320                 SelfKind::Explicit(this.parse_ty()?, m)
2321             } else {
2322                 SelfKind::Value(m)
2323             };
2324             Ok((eself, eself_ident, eself_hi))
2325         };
2326         // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2327         let recover_self_ptr = |this: &mut Self| {
2328             let msg = "cannot pass `self` by raw pointer";
2329             let span = this.token.span;
2330             this.struct_span_err(span, msg).span_label(span, msg).emit();
2331
2332             Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2333         };
2334
2335         // Parse optional `self` parameter of a method.
2336         // Only a limited set of initial token sequences is considered `self` parameters; anything
2337         // else is parsed as a normal function parameter list, so some lookahead is required.
2338         let eself_lo = self.token.span;
2339         let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2340             token::BinOp(token::And) => {
2341                 let eself = if is_isolated_self(self, 1) {
2342                     // `&self`
2343                     self.bump();
2344                     SelfKind::Region(None, Mutability::Not)
2345                 } else if is_isolated_mut_self(self, 1) {
2346                     // `&mut self`
2347                     self.bump();
2348                     self.bump();
2349                     SelfKind::Region(None, Mutability::Mut)
2350                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2351                     // `&'lt self`
2352                     self.bump();
2353                     let lt = self.expect_lifetime();
2354                     SelfKind::Region(Some(lt), Mutability::Not)
2355                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2356                     // `&'lt mut self`
2357                     self.bump();
2358                     let lt = self.expect_lifetime();
2359                     self.bump();
2360                     SelfKind::Region(Some(lt), Mutability::Mut)
2361                 } else {
2362                     // `&not_self`
2363                     return Ok(None);
2364                 };
2365                 (eself, expect_self_ident(self), self.prev_token.span)
2366             }
2367             // `*self`
2368             token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2369                 self.bump();
2370                 recover_self_ptr(self)?
2371             }
2372             // `*mut self` and `*const self`
2373             token::BinOp(token::Star)
2374                 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2375             {
2376                 self.bump();
2377                 self.bump();
2378                 recover_self_ptr(self)?
2379             }
2380             // `self` and `self: TYPE`
2381             token::Ident(..) if is_isolated_self(self, 0) => {
2382                 parse_self_possibly_typed(self, Mutability::Not)?
2383             }
2384             // `mut self` and `mut self: TYPE`
2385             token::Ident(..) if is_isolated_mut_self(self, 0) => {
2386                 self.bump();
2387                 parse_self_possibly_typed(self, Mutability::Mut)?
2388             }
2389             _ => return Ok(None),
2390         };
2391
2392         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2393         Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2394     }
2395
2396     fn is_named_param(&self) -> bool {
2397         let offset = match self.token.kind {
2398             token::Interpolated(ref nt) => match **nt {
2399                 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2400                 _ => 0,
2401             },
2402             token::BinOp(token::And) | token::AndAnd => 1,
2403             _ if self.token.is_keyword(kw::Mut) => 1,
2404             _ => 0,
2405         };
2406
2407         self.look_ahead(offset, |t| t.is_ident())
2408             && self.look_ahead(offset + 1, |t| t == &token::Colon)
2409     }
2410
2411     fn recover_first_param(&mut self) -> &'static str {
2412         match self
2413             .parse_outer_attributes()
2414             .and_then(|_| self.parse_self_param())
2415             .map_err(|e| e.cancel())
2416         {
2417             Ok(Some(_)) => "method",
2418             _ => "function",
2419         }
2420     }
2421 }
2422
2423 enum IsMacroRulesItem {
2424     Yes { has_bang: bool },
2425     No,
2426 }