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