]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/item.rs
Rollup merge of #103124 - ldm0:nohard_tests, r=Mark-Simulacrum
[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                 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
975             }
976         };
977
978         Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
979     }
980
981     /// Parses `*` or `{...}`.
982     fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
983         Ok(if self.eat(&token::BinOp(token::Star)) {
984             UseTreeKind::Glob
985         } else {
986             UseTreeKind::Nested(self.parse_use_tree_list()?)
987         })
988     }
989
990     /// Parses a `UseTreeKind::Nested(list)`.
991     ///
992     /// ```text
993     /// USE_TREE_LIST = Ã˜ | (USE_TREE `,`)* USE_TREE [`,`]
994     /// ```
995     fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
996         self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
997             .map(|(r, _)| r)
998     }
999
1000     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1001         if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1002     }
1003
1004     fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1005         match self.token.ident() {
1006             Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1007                 self.bump();
1008                 Ok(ident)
1009             }
1010             _ => self.parse_ident(),
1011         }
1012     }
1013
1014     /// Parses `extern crate` links.
1015     ///
1016     /// # Examples
1017     ///
1018     /// ```ignore (illustrative)
1019     /// extern crate foo;
1020     /// extern crate bar as foo;
1021     /// ```
1022     fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1023         // Accept `extern crate name-like-this` for better diagnostics
1024         let orig_name = self.parse_crate_name_with_dashes()?;
1025         let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1026             (rename, Some(orig_name.name))
1027         } else {
1028             (orig_name, None)
1029         };
1030         self.expect_semi()?;
1031         Ok((item_name, ItemKind::ExternCrate(orig_name)))
1032     }
1033
1034     fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1035         let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1036         let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1037                               in the code";
1038         let mut ident = if self.token.is_keyword(kw::SelfLower) {
1039             self.parse_path_segment_ident()
1040         } else {
1041             self.parse_ident()
1042         }?;
1043         let mut idents = vec![];
1044         let mut replacement = vec![];
1045         let mut fixed_crate_name = false;
1046         // Accept `extern crate name-like-this` for better diagnostics.
1047         let dash = token::BinOp(token::BinOpToken::Minus);
1048         if self.token == dash {
1049             // Do not include `-` as part of the expected tokens list.
1050             while self.eat(&dash) {
1051                 fixed_crate_name = true;
1052                 replacement.push((self.prev_token.span, "_".to_string()));
1053                 idents.push(self.parse_ident()?);
1054             }
1055         }
1056         if fixed_crate_name {
1057             let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1058             let mut fixed_name = ident.name.to_string();
1059             for part in idents {
1060                 fixed_name.push_str(&format!("_{}", part.name));
1061             }
1062             ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1063
1064             self.struct_span_err(fixed_name_sp, error_msg)
1065                 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1066                 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1067                 .emit();
1068         }
1069         Ok(ident)
1070     }
1071
1072     /// Parses `extern` for foreign ABIs modules.
1073     ///
1074     /// `extern` is expected to have been consumed before calling this method.
1075     ///
1076     /// # Examples
1077     ///
1078     /// ```ignore (only-for-syntax-highlight)
1079     /// extern "C" {}
1080     /// extern {}
1081     /// ```
1082     fn parse_item_foreign_mod(
1083         &mut self,
1084         attrs: &mut AttrVec,
1085         mut unsafety: Unsafe,
1086     ) -> PResult<'a, ItemInfo> {
1087         let abi = self.parse_abi(); // ABI?
1088         if unsafety == Unsafe::No
1089             && self.token.is_keyword(kw::Unsafe)
1090             && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1091         {
1092             let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1093             err.emit();
1094             unsafety = Unsafe::Yes(self.token.span);
1095             self.eat_keyword(kw::Unsafe);
1096         }
1097         let module = ast::ForeignMod {
1098             unsafety,
1099             abi,
1100             items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1101         };
1102         Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1103     }
1104
1105     /// Parses a foreign item (one in an `extern { ... }` block).
1106     pub fn parse_foreign_item(
1107         &mut self,
1108         force_collect: ForceCollect,
1109     ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1110         let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1111         Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1112             |Item { attrs, id, span, vis, ident, kind, tokens }| {
1113                 let kind = match ForeignItemKind::try_from(kind) {
1114                     Ok(kind) => kind,
1115                     Err(kind) => match kind {
1116                         ItemKind::Const(_, a, b) => {
1117                             self.error_on_foreign_const(span, ident);
1118                             ForeignItemKind::Static(a, Mutability::Not, b)
1119                         }
1120                         _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1121                     },
1122                 };
1123                 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1124             },
1125         ))
1126     }
1127
1128     fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1129         let span = self.sess.source_map().guess_head_span(span);
1130         let descr = kind.descr();
1131         self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1132             .help(&format!("consider moving the {descr} out to a nearby module scope"))
1133             .emit();
1134         None
1135     }
1136
1137     fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1138         self.struct_span_err(ident.span, "extern items cannot be `const`")
1139             .span_suggestion(
1140                 span.with_hi(ident.span.lo()),
1141                 "try using a static value",
1142                 "static ",
1143                 Applicability::MachineApplicable,
1144             )
1145             .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1146             .emit();
1147     }
1148
1149     fn is_unsafe_foreign_mod(&self) -> bool {
1150         self.token.is_keyword(kw::Unsafe)
1151             && self.is_keyword_ahead(1, &[kw::Extern])
1152             && self.look_ahead(
1153                 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1154                 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1155             )
1156     }
1157
1158     fn is_static_global(&mut self) -> bool {
1159         if self.check_keyword(kw::Static) {
1160             // Check if this could be a closure.
1161             !self.look_ahead(1, |token| {
1162                 if token.is_keyword(kw::Move) {
1163                     return true;
1164                 }
1165                 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1166             })
1167         } else {
1168             false
1169         }
1170     }
1171
1172     /// Recover on `const mut` with `const` already eaten.
1173     fn recover_const_mut(&mut self, const_span: Span) {
1174         if self.eat_keyword(kw::Mut) {
1175             let span = self.prev_token.span;
1176             self.struct_span_err(span, "const globals cannot be mutable")
1177                 .span_label(span, "cannot be mutable")
1178                 .span_suggestion(
1179                     const_span,
1180                     "you might want to declare a static instead",
1181                     "static",
1182                     Applicability::MaybeIncorrect,
1183                 )
1184                 .emit();
1185         } else if self.eat_keyword(kw::Let) {
1186             let span = self.prev_token.span;
1187             self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1188                 .span_suggestion(
1189                     const_span.to(span),
1190                     "remove `let`",
1191                     "const",
1192                     Applicability::MaybeIncorrect,
1193                 )
1194                 .emit();
1195         }
1196     }
1197
1198     /// Recover on `const impl` with `const` already eaten.
1199     fn recover_const_impl(
1200         &mut self,
1201         const_span: Span,
1202         attrs: &mut AttrVec,
1203         defaultness: Defaultness,
1204     ) -> PResult<'a, ItemInfo> {
1205         let impl_span = self.token.span;
1206         let mut err = self.expected_ident_found();
1207
1208         // Only try to recover if this is implementing a trait for a type
1209         let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1210             Ok(impl_info) => impl_info,
1211             Err(recovery_error) => {
1212                 // Recovery failed, raise the "expected identifier" error
1213                 recovery_error.cancel();
1214                 return Err(err);
1215             }
1216         };
1217
1218         match impl_info.1 {
1219             ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1220                 *constness = Const::Yes(const_span);
1221
1222                 let before_trait = trai.path.span.shrink_to_lo();
1223                 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1224                 err.multipart_suggestion(
1225                     "you might have meant to write a const trait impl",
1226                     vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1227                     Applicability::MaybeIncorrect,
1228                 )
1229                 .emit();
1230             }
1231             ItemKind::Impl { .. } => return Err(err),
1232             _ => unreachable!(),
1233         }
1234
1235         Ok(impl_info)
1236     }
1237
1238     /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1239     /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1240     ///
1241     /// When `m` is `"const"`, `$ident` may also be `"_"`.
1242     fn parse_item_global(
1243         &mut self,
1244         m: Option<Mutability>,
1245     ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1246         let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1247
1248         // Parse the type of a `const` or `static mut?` item.
1249         // That is, the `":" $ty` fragment.
1250         let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1251         {
1252             // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1253             (true, false) => self.parse_ty()?,
1254             (colon, _) => self.recover_missing_const_type(colon, m),
1255         };
1256
1257         let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1258         self.expect_semi()?;
1259         Ok((id, ty, expr))
1260     }
1261
1262     /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1263     /// This means that the type is missing.
1264     fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1265         // Construct the error and stash it away with the hope
1266         // that typeck will later enrich the error with a type.
1267         let kind = match m {
1268             Some(Mutability::Mut) => "static mut",
1269             Some(Mutability::Not) => "static",
1270             None => "const",
1271         };
1272
1273         let colon = match colon_present {
1274             true => "",
1275             false => ":",
1276         };
1277
1278         let span = self.prev_token.span.shrink_to_hi();
1279         let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1280         err.span_suggestion(
1281             span,
1282             "provide a type for the item",
1283             format!("{colon} <type>"),
1284             Applicability::HasPlaceholders,
1285         );
1286         err.stash(span, StashKey::ItemNoType);
1287
1288         // The user intended that the type be inferred,
1289         // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1290         P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1291     }
1292
1293     /// Parses an enum declaration.
1294     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1295         if self.token.is_keyword(kw::Struct) {
1296             let span = self.prev_token.span.to(self.token.span);
1297             let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1298             err.span_suggestion(
1299                 span,
1300                 "replace `enum struct` with",
1301                 "enum",
1302                 Applicability::MachineApplicable,
1303             );
1304             if self.look_ahead(1, |t| t.is_ident()) {
1305                 self.bump();
1306                 err.emit();
1307             } else {
1308                 return Err(err);
1309             }
1310         }
1311
1312         let id = self.parse_ident()?;
1313         let mut generics = self.parse_generics()?;
1314         generics.where_clause = self.parse_where_clause()?;
1315
1316         // Possibly recover `enum Foo;` instead of `enum Foo {}`
1317         let (variants, _) = if self.token == TokenKind::Semi {
1318             self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1319             self.bump();
1320             (vec![], false)
1321         } else {
1322             self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1323                 |mut e| {
1324                     e.span_label(id.span, "while parsing this enum");
1325                     self.recover_stmt();
1326                     e
1327                 },
1328             )?
1329         };
1330
1331         let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1332         Ok((id, ItemKind::Enum(enum_definition, generics)))
1333     }
1334
1335     fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1336         let variant_attrs = self.parse_outer_attributes()?;
1337         self.collect_tokens_trailing_token(
1338             variant_attrs,
1339             ForceCollect::No,
1340             |this, variant_attrs| {
1341                 let vlo = this.token.span;
1342
1343                 let vis = this.parse_visibility(FollowedByType::No)?;
1344                 if !this.recover_nested_adt_item(kw::Enum)? {
1345                     return Ok((None, TrailingToken::None));
1346                 }
1347                 let ident = this.parse_field_ident("enum", vlo)?;
1348
1349                 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1350                     // Parse a struct variant.
1351                     let (fields, recovered) =
1352                         this.parse_record_struct_body("struct", ident.span, false)?;
1353                     VariantData::Struct(fields, recovered)
1354                 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1355                     VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1356                 } else {
1357                     VariantData::Unit(DUMMY_NODE_ID)
1358                 };
1359
1360                 let disr_expr =
1361                     if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1362
1363                 let vr = ast::Variant {
1364                     ident,
1365                     vis,
1366                     id: DUMMY_NODE_ID,
1367                     attrs: variant_attrs,
1368                     data: struct_def,
1369                     disr_expr,
1370                     span: vlo.to(this.prev_token.span),
1371                     is_placeholder: false,
1372                 };
1373
1374                 Ok((Some(vr), TrailingToken::MaybeComma))
1375             },
1376         )
1377     }
1378
1379     /// Parses `struct Foo { ... }`.
1380     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1381         let class_name = self.parse_ident()?;
1382
1383         let mut generics = self.parse_generics()?;
1384
1385         // There is a special case worth noting here, as reported in issue #17904.
1386         // If we are parsing a tuple struct it is the case that the where clause
1387         // should follow the field list. Like so:
1388         //
1389         // struct Foo<T>(T) where T: Copy;
1390         //
1391         // If we are parsing a normal record-style struct it is the case
1392         // that the where clause comes before the body, and after the generics.
1393         // So if we look ahead and see a brace or a where-clause we begin
1394         // parsing a record style struct.
1395         //
1396         // Otherwise if we look ahead and see a paren we parse a tuple-style
1397         // struct.
1398
1399         let vdata = if self.token.is_keyword(kw::Where) {
1400             generics.where_clause = self.parse_where_clause()?;
1401             if self.eat(&token::Semi) {
1402                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1403                 VariantData::Unit(DUMMY_NODE_ID)
1404             } else {
1405                 // If we see: `struct Foo<T> where T: Copy { ... }`
1406                 let (fields, recovered) = self.parse_record_struct_body(
1407                     "struct",
1408                     class_name.span,
1409                     generics.where_clause.has_where_token,
1410                 )?;
1411                 VariantData::Struct(fields, recovered)
1412             }
1413         // No `where` so: `struct Foo<T>;`
1414         } else if self.eat(&token::Semi) {
1415             VariantData::Unit(DUMMY_NODE_ID)
1416         // Record-style struct definition
1417         } else if self.token == token::OpenDelim(Delimiter::Brace) {
1418             let (fields, recovered) = self.parse_record_struct_body(
1419                 "struct",
1420                 class_name.span,
1421                 generics.where_clause.has_where_token,
1422             )?;
1423             VariantData::Struct(fields, recovered)
1424         // Tuple-style struct definition with optional where-clause.
1425         } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1426             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1427             generics.where_clause = self.parse_where_clause()?;
1428             self.expect_semi()?;
1429             body
1430         } else {
1431             let token_str = super::token_descr(&self.token);
1432             let msg = &format!(
1433                 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1434             );
1435             let mut err = self.struct_span_err(self.token.span, msg);
1436             err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1437             return Err(err);
1438         };
1439
1440         Ok((class_name, ItemKind::Struct(vdata, generics)))
1441     }
1442
1443     /// Parses `union Foo { ... }`.
1444     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1445         let class_name = self.parse_ident()?;
1446
1447         let mut generics = self.parse_generics()?;
1448
1449         let vdata = if self.token.is_keyword(kw::Where) {
1450             generics.where_clause = self.parse_where_clause()?;
1451             let (fields, recovered) = self.parse_record_struct_body(
1452                 "union",
1453                 class_name.span,
1454                 generics.where_clause.has_where_token,
1455             )?;
1456             VariantData::Struct(fields, recovered)
1457         } else if self.token == token::OpenDelim(Delimiter::Brace) {
1458             let (fields, recovered) = self.parse_record_struct_body(
1459                 "union",
1460                 class_name.span,
1461                 generics.where_clause.has_where_token,
1462             )?;
1463             VariantData::Struct(fields, recovered)
1464         } else {
1465             let token_str = super::token_descr(&self.token);
1466             let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1467             let mut err = self.struct_span_err(self.token.span, msg);
1468             err.span_label(self.token.span, "expected `where` or `{` after union name");
1469             return Err(err);
1470         };
1471
1472         Ok((class_name, ItemKind::Union(vdata, generics)))
1473     }
1474
1475     fn parse_record_struct_body(
1476         &mut self,
1477         adt_ty: &str,
1478         ident_span: Span,
1479         parsed_where: bool,
1480     ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1481         let mut fields = Vec::new();
1482         let mut recovered = false;
1483         if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1484             while self.token != token::CloseDelim(Delimiter::Brace) {
1485                 let field = self.parse_field_def(adt_ty).map_err(|e| {
1486                     self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1487                     recovered = true;
1488                     e
1489                 });
1490                 match field {
1491                     Ok(field) => fields.push(field),
1492                     Err(mut err) => {
1493                         err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1494                         err.emit();
1495                         break;
1496                     }
1497                 }
1498             }
1499             self.eat(&token::CloseDelim(Delimiter::Brace));
1500         } else {
1501             let token_str = super::token_descr(&self.token);
1502             let msg = &format!(
1503                 "expected {}`{{` after struct name, found {}",
1504                 if parsed_where { "" } else { "`where`, or " },
1505                 token_str
1506             );
1507             let mut err = self.struct_span_err(self.token.span, msg);
1508             err.span_label(
1509                 self.token.span,
1510                 format!(
1511                     "expected {}`{{` after struct name",
1512                     if parsed_where { "" } else { "`where`, or " }
1513                 ),
1514             );
1515             return Err(err);
1516         }
1517
1518         Ok((fields, recovered))
1519     }
1520
1521     fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1522         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1523         // Unit like structs are handled in parse_item_struct function
1524         self.parse_paren_comma_seq(|p| {
1525             let attrs = p.parse_outer_attributes()?;
1526             p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1527                 let lo = p.token.span;
1528                 let vis = p.parse_visibility(FollowedByType::Yes)?;
1529                 let ty = p.parse_ty()?;
1530
1531                 Ok((
1532                     FieldDef {
1533                         span: lo.to(ty.span),
1534                         vis,
1535                         ident: None,
1536                         id: DUMMY_NODE_ID,
1537                         ty,
1538                         attrs,
1539                         is_placeholder: false,
1540                     },
1541                     TrailingToken::MaybeComma,
1542                 ))
1543             })
1544         })
1545         .map(|(r, _)| r)
1546     }
1547
1548     /// Parses an element of a struct declaration.
1549     fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1550         let attrs = self.parse_outer_attributes()?;
1551         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1552             let lo = this.token.span;
1553             let vis = this.parse_visibility(FollowedByType::No)?;
1554             Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1555         })
1556     }
1557
1558     /// Parses a structure field declaration.
1559     fn parse_single_struct_field(
1560         &mut self,
1561         adt_ty: &str,
1562         lo: Span,
1563         vis: Visibility,
1564         attrs: AttrVec,
1565     ) -> PResult<'a, FieldDef> {
1566         let mut seen_comma: bool = false;
1567         let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1568         if self.token == token::Comma {
1569             seen_comma = true;
1570         }
1571         if self.eat(&token::Semi) {
1572             let sp = self.prev_token.span;
1573             let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1574             err.span_suggestion_short(
1575                 sp,
1576                 "replace `;` with `,`",
1577                 ",",
1578                 Applicability::MachineApplicable,
1579             );
1580             return Err(err);
1581         }
1582         match self.token.kind {
1583             token::Comma => {
1584                 self.bump();
1585             }
1586             token::CloseDelim(Delimiter::Brace) => {}
1587             token::DocComment(..) => {
1588                 let previous_span = self.prev_token.span;
1589                 let mut err = DocCommentDoesNotDocumentAnything {
1590                     span: self.token.span,
1591                     missing_comma: None,
1592                 };
1593                 self.bump(); // consume the doc comment
1594                 let comma_after_doc_seen = self.eat(&token::Comma);
1595                 // `seen_comma` is always false, because we are inside doc block
1596                 // condition is here to make code more readable
1597                 if !seen_comma && comma_after_doc_seen {
1598                     seen_comma = true;
1599                 }
1600                 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1601                     self.sess.emit_err(err);
1602                 } else {
1603                     if !seen_comma {
1604                         let sp = previous_span.shrink_to_hi();
1605                         err.missing_comma = Some(sp);
1606                     }
1607                     return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1608                 }
1609             }
1610             _ => {
1611                 let sp = self.prev_token.span.shrink_to_hi();
1612                 let mut err = self.struct_span_err(
1613                     sp,
1614                     &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1615                 );
1616
1617                 // Try to recover extra trailing angle brackets
1618                 let mut recovered = false;
1619                 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1620                     if let Some(last_segment) = segments.last() {
1621                         recovered = self.check_trailing_angle_brackets(
1622                             last_segment,
1623                             &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1624                         );
1625                         if recovered {
1626                             // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1627                             // after the comma
1628                             self.eat(&token::Comma);
1629                             // `check_trailing_angle_brackets` already emitted a nicer error
1630                             // NOTE(eddyb) this was `.cancel()`, but `err`
1631                             // gets returned, so we can't fully defuse it.
1632                             err.delay_as_bug();
1633                         }
1634                     }
1635                 }
1636
1637                 if self.token.is_ident()
1638                     || (self.token.kind == TokenKind::Pound
1639                         && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1640                 {
1641                     // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1642                     // emit the diagnostic and keep going
1643                     err.span_suggestion(
1644                         sp,
1645                         "try adding a comma",
1646                         ",",
1647                         Applicability::MachineApplicable,
1648                     );
1649                     err.emit();
1650                     recovered = true;
1651                 }
1652
1653                 if recovered {
1654                     // Make sure an error was emitted (either by recovering an angle bracket,
1655                     // or by finding an identifier as the next token), since we're
1656                     // going to continue parsing
1657                     assert!(self.sess.span_diagnostic.has_errors().is_some());
1658                 } else {
1659                     return Err(err);
1660                 }
1661             }
1662         }
1663         Ok(a_var)
1664     }
1665
1666     fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1667         if let Err(mut err) = self.expect(&token::Colon) {
1668             let sm = self.sess.source_map();
1669             let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1670             let semi_typo = self.token.kind == token::Semi
1671                 && self.look_ahead(1, |t| {
1672                     t.is_path_start()
1673                     // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1674                     // when there's no type and `;` was used instead of a comma.
1675                     && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1676                         (Ok(l), Ok(r)) => l.line == r.line,
1677                         _ => true,
1678                     }
1679                 });
1680             if eq_typo || semi_typo {
1681                 self.bump();
1682                 // Gracefully handle small typos.
1683                 err.span_suggestion_short(
1684                     self.prev_token.span,
1685                     "field names and their types are separated with `:`",
1686                     ":",
1687                     Applicability::MachineApplicable,
1688                 );
1689                 err.emit();
1690             } else {
1691                 return Err(err);
1692             }
1693         }
1694         Ok(())
1695     }
1696
1697     /// Parses a structure field.
1698     fn parse_name_and_ty(
1699         &mut self,
1700         adt_ty: &str,
1701         lo: Span,
1702         vis: Visibility,
1703         attrs: AttrVec,
1704     ) -> PResult<'a, FieldDef> {
1705         let name = self.parse_field_ident(adt_ty, lo)?;
1706         self.expect_field_ty_separator()?;
1707         let ty = self.parse_ty()?;
1708         if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1709             self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1710                 .span_suggestion_verbose(
1711                     self.token.span,
1712                     "write a path separator here",
1713                     "::",
1714                     Applicability::MaybeIncorrect,
1715                 )
1716                 .emit();
1717         }
1718         if self.token.kind == token::Eq {
1719             self.bump();
1720             let const_expr = self.parse_anon_const_expr()?;
1721             let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1722             self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1723                 .span_suggestion(
1724                     sp,
1725                     "remove this unsupported default value",
1726                     "",
1727                     Applicability::MachineApplicable,
1728                 )
1729                 .emit();
1730         }
1731         Ok(FieldDef {
1732             span: lo.to(self.prev_token.span),
1733             ident: Some(name),
1734             vis,
1735             id: DUMMY_NODE_ID,
1736             ty,
1737             attrs,
1738             is_placeholder: false,
1739         })
1740     }
1741
1742     /// Parses a field identifier. Specialized version of `parse_ident_common`
1743     /// for better diagnostics and suggestions.
1744     fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1745         let (ident, is_raw) = self.ident_or_err()?;
1746         if !is_raw && ident.is_reserved() {
1747             let snapshot = self.create_snapshot_for_diagnostic();
1748             let err = if self.check_fn_front_matter(false) {
1749                 let inherited_vis = Visibility {
1750                     span: rustc_span::DUMMY_SP,
1751                     kind: VisibilityKind::Inherited,
1752                     tokens: None,
1753                 };
1754                 // We use `parse_fn` to get a span for the function
1755                 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1756                 match self.parse_fn(&mut AttrVec::new(), fn_parse_mode, lo, &inherited_vis) {
1757                     Ok(_) => {
1758                         let mut err = self.struct_span_err(
1759                             lo.to(self.prev_token.span),
1760                             &format!("functions are not allowed in {adt_ty} definitions"),
1761                         );
1762                         err.help(
1763                             "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1764                         );
1765                         err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1766                         err
1767                     }
1768                     Err(err) => {
1769                         err.cancel();
1770                         self.restore_snapshot(snapshot);
1771                         self.expected_ident_found()
1772                     }
1773                 }
1774             } else if self.eat_keyword(kw::Struct) {
1775                 match self.parse_item_struct() {
1776                     Ok((ident, _)) => {
1777                         let mut err = self.struct_span_err(
1778                             lo.with_hi(ident.span.hi()),
1779                             &format!("structs are not allowed in {adt_ty} definitions"),
1780                         );
1781                         err.help("consider creating a new `struct` definition instead of nesting");
1782                         err
1783                     }
1784                     Err(err) => {
1785                         err.cancel();
1786                         self.restore_snapshot(snapshot);
1787                         self.expected_ident_found()
1788                     }
1789                 }
1790             } else {
1791                 let mut err = self.expected_ident_found();
1792                 if self.eat_keyword_noexpect(kw::Let)
1793                     && let removal_span = self.prev_token.span.until(self.token.span)
1794                     && let Ok(ident) = self.parse_ident_common(false)
1795                         // Cancel this error, we don't need it.
1796                         .map_err(|err| err.cancel())
1797                     && self.token.kind == TokenKind::Colon
1798                 {
1799                     err.span_suggestion(
1800                         removal_span,
1801                         "remove this `let` keyword",
1802                         String::new(),
1803                         Applicability::MachineApplicable,
1804                     );
1805                     err.note("the `let` keyword is not allowed in `struct` fields");
1806                     err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1807                     err.emit();
1808                     return Ok(ident);
1809                 } else {
1810                     self.restore_snapshot(snapshot);
1811                 }
1812                 err
1813             };
1814             return Err(err);
1815         }
1816         self.bump();
1817         Ok(ident)
1818     }
1819
1820     /// Parses a declarative macro 2.0 definition.
1821     /// The `macro` keyword has already been parsed.
1822     /// ```ebnf
1823     /// MacBody = "{" TOKEN_STREAM "}" ;
1824     /// MacParams = "(" TOKEN_STREAM ")" ;
1825     /// DeclMac = "macro" Ident MacParams? MacBody ;
1826     /// ```
1827     fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1828         let ident = self.parse_ident()?;
1829         let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1830             self.parse_mac_args()? // `MacBody`
1831         } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1832             let params = self.parse_token_tree(); // `MacParams`
1833             let pspan = params.span();
1834             if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1835                 return self.unexpected();
1836             }
1837             let body = self.parse_token_tree(); // `MacBody`
1838             // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1839             let bspan = body.span();
1840             let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1841             let tokens = TokenStream::new(vec![params, arrow, body]);
1842             let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1843             P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1844         } else {
1845             return self.unexpected();
1846         };
1847
1848         self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1849         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1850     }
1851
1852     /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1853     fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1854         if self.check_keyword(kw::MacroRules) {
1855             let macro_rules_span = self.token.span;
1856
1857             if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1858                 return IsMacroRulesItem::Yes { has_bang: true };
1859             } else if self.look_ahead(1, |t| (t.is_ident())) {
1860                 // macro_rules foo
1861                 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1862                     .span_suggestion(
1863                         macro_rules_span,
1864                         "add a `!`",
1865                         "macro_rules!",
1866                         Applicability::MachineApplicable,
1867                     )
1868                     .emit();
1869
1870                 return IsMacroRulesItem::Yes { has_bang: false };
1871             }
1872         }
1873
1874         IsMacroRulesItem::No
1875     }
1876
1877     /// Parses a `macro_rules! foo { ... }` declarative macro.
1878     fn parse_item_macro_rules(
1879         &mut self,
1880         vis: &Visibility,
1881         has_bang: bool,
1882     ) -> PResult<'a, ItemInfo> {
1883         self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1884
1885         if has_bang {
1886             self.expect(&token::Not)?; // `!`
1887         }
1888         let ident = self.parse_ident()?;
1889
1890         if self.eat(&token::Not) {
1891             // Handle macro_rules! foo!
1892             let span = self.prev_token.span;
1893             self.struct_span_err(span, "macro names aren't followed by a `!`")
1894                 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1895                 .emit();
1896         }
1897
1898         let body = self.parse_mac_args()?;
1899         self.eat_semi_for_macro_if_needed(&body);
1900         self.complain_if_pub_macro(vis, true);
1901
1902         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1903     }
1904
1905     /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1906     /// If that's not the case, emit an error.
1907     fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1908         if let VisibilityKind::Inherited = vis.kind {
1909             return;
1910         }
1911
1912         let vstr = pprust::vis_to_string(vis);
1913         let vstr = vstr.trim_end();
1914         if macro_rules {
1915             let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1916             self.struct_span_err(vis.span, &msg)
1917                 .span_suggestion(
1918                     vis.span,
1919                     "try exporting the macro",
1920                     "#[macro_export]",
1921                     Applicability::MaybeIncorrect, // speculative
1922                 )
1923                 .emit();
1924         } else {
1925             self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1926                 .span_suggestion(
1927                     vis.span,
1928                     "remove the visibility",
1929                     "",
1930                     Applicability::MachineApplicable,
1931                 )
1932                 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1933                 .emit();
1934         }
1935     }
1936
1937     fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1938         if args.need_semicolon() && !self.eat(&token::Semi) {
1939             self.report_invalid_macro_expansion_item(args);
1940         }
1941     }
1942
1943     fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1944         let span = args.span().expect("undelimited macro call");
1945         let mut err = self.struct_span_err(
1946             span,
1947             "macros that expand to items must be delimited with braces or followed by a semicolon",
1948         );
1949         // FIXME: This will make us not emit the help even for declarative
1950         // macros within the same crate (that we can fix), which is sad.
1951         if !span.from_expansion() {
1952             if self.unclosed_delims.is_empty() {
1953                 let DelimSpan { open, close } = match args {
1954                     MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1955                     MacArgs::Delimited(dspan, ..) => *dspan,
1956                 };
1957                 err.multipart_suggestion(
1958                     "change the delimiters to curly braces",
1959                     vec![(open, "{".to_string()), (close, '}'.to_string())],
1960                     Applicability::MaybeIncorrect,
1961                 );
1962             } else {
1963                 err.span_suggestion(
1964                     span,
1965                     "change the delimiters to curly braces",
1966                     " { /* items */ }",
1967                     Applicability::HasPlaceholders,
1968                 );
1969             }
1970             err.span_suggestion(
1971                 span.shrink_to_hi(),
1972                 "add a semicolon",
1973                 ';',
1974                 Applicability::MaybeIncorrect,
1975             );
1976         }
1977         err.emit();
1978     }
1979
1980     /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1981     /// it is, we try to parse the item and report error about nested types.
1982     fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1983         if (self.token.is_keyword(kw::Enum)
1984             || self.token.is_keyword(kw::Struct)
1985             || self.token.is_keyword(kw::Union))
1986             && self.look_ahead(1, |t| t.is_ident())
1987         {
1988             let kw_token = self.token.clone();
1989             let kw_str = pprust::token_to_string(&kw_token);
1990             let item = self.parse_item(ForceCollect::No)?;
1991
1992             self.struct_span_err(
1993                 kw_token.span,
1994                 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
1995             )
1996             .span_suggestion(
1997                 item.unwrap().span,
1998                 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
1999                 "",
2000                 Applicability::MaybeIncorrect,
2001             )
2002             .emit();
2003             // We successfully parsed the item but we must inform the caller about nested problem.
2004             return Ok(false);
2005         }
2006         Ok(true)
2007     }
2008 }
2009
2010 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2011 ///
2012 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2013 ///
2014 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2015 /// were allowed to omit parameter names. In 2018, they became required.
2016 type ReqName = fn(Edition) -> bool;
2017
2018 /// Parsing configuration for functions.
2019 ///
2020 /// The syntax of function items is slightly different within trait definitions,
2021 /// impl blocks, and modules. It is still parsed using the same code, just with
2022 /// different flags set, so that even when the input is wrong and produces a parse
2023 /// error, it still gets into the AST and the rest of the parser and
2024 /// type checker can run.
2025 #[derive(Clone, Copy)]
2026 pub(crate) struct FnParseMode {
2027     /// A function pointer that decides if, per-parameter `p`, `p` must have a
2028     /// pattern or just a type. This field affects parsing of the parameters list.
2029     ///
2030     /// ```text
2031     /// fn foo(alef: A) -> X { X::new() }
2032     ///        -----^^ affects parsing this part of the function signature
2033     ///        |
2034     ///        if req_name returns false, then this name is optional
2035     ///
2036     /// fn bar(A) -> X;
2037     ///        ^
2038     ///        |
2039     ///        if req_name returns true, this is an error
2040     /// ```
2041     ///
2042     /// Calling this function pointer should only return false if:
2043     ///
2044     ///   * The item is being parsed inside of a trait definition.
2045     ///     Within an impl block or a module, it should always evaluate
2046     ///     to true.
2047     ///   * The span is from Edition 2015. In particular, you can get a
2048     ///     2015 span inside a 2021 crate using macros.
2049     pub req_name: ReqName,
2050     /// If this flag is set to `true`, then plain, semicolon-terminated function
2051     /// prototypes are not allowed here.
2052     ///
2053     /// ```text
2054     /// fn foo(alef: A) -> X { X::new() }
2055     ///                      ^^^^^^^^^^^^
2056     ///                      |
2057     ///                      this is always allowed
2058     ///
2059     /// fn bar(alef: A, bet: B) -> X;
2060     ///                             ^
2061     ///                             |
2062     ///                             if req_body is set to true, this is an error
2063     /// ```
2064     ///
2065     /// This field should only be set to false if the item is inside of a trait
2066     /// definition or extern block. Within an impl block or a module, it should
2067     /// always be set to true.
2068     pub req_body: bool,
2069 }
2070
2071 /// Parsing of functions and methods.
2072 impl<'a> Parser<'a> {
2073     /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2074     fn parse_fn(
2075         &mut self,
2076         attrs: &mut AttrVec,
2077         fn_parse_mode: FnParseMode,
2078         sig_lo: Span,
2079         vis: &Visibility,
2080     ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2081         let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
2082         let ident = self.parse_ident()?; // `foo`
2083         let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2084         let decl =
2085             self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
2086         generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2087
2088         let mut sig_hi = self.prev_token.span;
2089         let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2090         let fn_sig_span = sig_lo.to(sig_hi);
2091         Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2092     }
2093
2094     /// Parse the "body" of a function.
2095     /// This can either be `;` when there's no body,
2096     /// or e.g. a block when the function is a provided one.
2097     fn parse_fn_body(
2098         &mut self,
2099         attrs: &mut AttrVec,
2100         ident: &Ident,
2101         sig_hi: &mut Span,
2102         req_body: bool,
2103     ) -> PResult<'a, Option<P<Block>>> {
2104         let has_semi = if req_body {
2105             self.token.kind == TokenKind::Semi
2106         } else {
2107             // Only include `;` in list of expected tokens if body is not required
2108             self.check(&TokenKind::Semi)
2109         };
2110         let (inner_attrs, body) = if has_semi {
2111             // Include the trailing semicolon in the span of the signature
2112             self.expect_semi()?;
2113             *sig_hi = self.prev_token.span;
2114             (AttrVec::new(), None)
2115         } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2116             self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2117         } else if self.token.kind == token::Eq {
2118             // Recover `fn foo() = $expr;`.
2119             self.bump(); // `=`
2120             let eq_sp = self.prev_token.span;
2121             let _ = self.parse_expr()?;
2122             self.expect_semi()?; // `;`
2123             let span = eq_sp.to(self.prev_token.span);
2124             self.struct_span_err(span, "function body cannot be `= expression;`")
2125                 .multipart_suggestion(
2126                     "surround the expression with `{` and `}` instead of `=` and `;`",
2127                     vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2128                     Applicability::MachineApplicable,
2129                 )
2130                 .emit();
2131             (AttrVec::new(), Some(self.mk_block_err(span)))
2132         } else {
2133             let expected = if req_body {
2134                 &[token::OpenDelim(Delimiter::Brace)][..]
2135             } else {
2136                 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2137             };
2138             if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2139                 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2140                     // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2141                     // the AST for typechecking.
2142                     err.span_label(ident.span, "while parsing this `fn`");
2143                     err.emit();
2144                 } else {
2145                     return Err(err);
2146                 }
2147             }
2148             (AttrVec::new(), None)
2149         };
2150         attrs.extend(inner_attrs);
2151         Ok(body)
2152     }
2153
2154     /// Is the current token the start of an `FnHeader` / not a valid parse?
2155     ///
2156     /// `check_pub` adds additional `pub` to the checks in case users place it
2157     /// wrongly, can be used to ensure `pub` never comes after `default`.
2158     pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
2159         // We use an over-approximation here.
2160         // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2161         // `pub` is added in case users got confused with the ordering like `async pub fn`,
2162         // only if it wasn't preceded by `default` as `default pub` is invalid.
2163         let quals: &[Symbol] = if check_pub {
2164             &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2165         } else {
2166             &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2167         };
2168         self.check_keyword(kw::Fn) // Definitely an `fn`.
2169             // `$qual fn` or `$qual $qual`:
2170             || quals.iter().any(|&kw| self.check_keyword(kw))
2171                 && self.look_ahead(1, |t| {
2172                     // `$qual fn`, e.g. `const fn` or `async fn`.
2173                     t.is_keyword(kw::Fn)
2174                     // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2175                     || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
2176                         // Rule out 2015 `const async: T = val`.
2177                         && i.is_reserved()
2178                         // Rule out unsafe extern block.
2179                         && !self.is_unsafe_foreign_mod())
2180                 })
2181             // `extern ABI fn`
2182             || self.check_keyword(kw::Extern)
2183                 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2184                 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
2185     }
2186
2187     /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2188     /// up to and including the `fn` keyword. The formal grammar is:
2189     ///
2190     /// ```text
2191     /// Extern = "extern" StringLit? ;
2192     /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2193     /// FnFrontMatter = FnQual "fn" ;
2194     /// ```
2195     ///
2196     /// `vis` represents the visibility that was already parsed, if any. Use
2197     /// `Visibility::Inherited` when no visibility is known.
2198     pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2199         let sp_start = self.token.span;
2200         let constness = self.parse_constness();
2201
2202         let async_start_sp = self.token.span;
2203         let asyncness = self.parse_asyncness();
2204
2205         let unsafe_start_sp = self.token.span;
2206         let unsafety = self.parse_unsafety();
2207
2208         let ext_start_sp = self.token.span;
2209         let ext = self.parse_extern();
2210
2211         if let Async::Yes { span, .. } = asyncness {
2212             self.ban_async_in_2015(span);
2213         }
2214
2215         if !self.eat_keyword(kw::Fn) {
2216             // It is possible for `expect_one_of` to recover given the contents of
2217             // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2218             // account for this.
2219             match self.expect_one_of(&[], &[]) {
2220                 Ok(true) => {}
2221                 Ok(false) => unreachable!(),
2222                 Err(mut err) => {
2223                     // Qualifier keywords ordering check
2224                     enum WrongKw {
2225                         Duplicated(Span),
2226                         Misplaced(Span),
2227                     }
2228
2229                     // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2230                     // that the keyword is already present and the second instance should be removed.
2231                     let wrong_kw = if self.check_keyword(kw::Const) {
2232                         match constness {
2233                             Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2234                             Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2235                         }
2236                     } else if self.check_keyword(kw::Async) {
2237                         match asyncness {
2238                             Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2239                             Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2240                         }
2241                     } else if self.check_keyword(kw::Unsafe) {
2242                         match unsafety {
2243                             Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2244                             Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2245                         }
2246                     } else {
2247                         None
2248                     };
2249
2250                     // The keyword is already present, suggest removal of the second instance
2251                     if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2252                         let original_kw = self
2253                             .span_to_snippet(original_sp)
2254                             .expect("Span extracted directly from keyword should always work");
2255
2256                         err.span_suggestion(
2257                             self.token.uninterpolated_span(),
2258                             &format!("`{original_kw}` already used earlier, remove this one"),
2259                             "",
2260                             Applicability::MachineApplicable,
2261                         )
2262                         .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2263                     }
2264                     // The keyword has not been seen yet, suggest correct placement in the function front matter
2265                     else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2266                         let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2267                         if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2268                             let misplaced_qual_sp = self.token.uninterpolated_span();
2269                             let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2270
2271                             err.span_suggestion(
2272                                     correct_pos_sp.to(misplaced_qual_sp),
2273                                     &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2274                                     format!("{misplaced_qual} {current_qual}"),
2275                                     Applicability::MachineApplicable,
2276                                 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2277                         }
2278                     }
2279                     // Recover incorrect visibility order such as `async pub`
2280                     else if self.check_keyword(kw::Pub) {
2281                         let sp = sp_start.to(self.prev_token.span);
2282                         if let Ok(snippet) = self.span_to_snippet(sp) {
2283                             let current_vis = match self.parse_visibility(FollowedByType::No) {
2284                                 Ok(v) => v,
2285                                 Err(d) => {
2286                                     d.cancel();
2287                                     return Err(err);
2288                                 }
2289                             };
2290                             let vs = pprust::vis_to_string(&current_vis);
2291                             let vs = vs.trim_end();
2292
2293                             // There was no explicit visibility
2294                             if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2295                                 err.span_suggestion(
2296                                     sp_start.to(self.prev_token.span),
2297                                     &format!("visibility `{vs}` must come before `{snippet}`"),
2298                                     format!("{vs} {snippet}"),
2299                                     Applicability::MachineApplicable,
2300                                 );
2301                             }
2302                             // There was an explicit visibility
2303                             else {
2304                                 err.span_suggestion(
2305                                     current_vis.span,
2306                                     "there is already a visibility modifier, remove one",
2307                                     "",
2308                                     Applicability::MachineApplicable,
2309                                 )
2310                                 .span_note(orig_vis.span, "explicit visibility first seen here");
2311                             }
2312                         }
2313                     }
2314                     return Err(err);
2315                 }
2316             }
2317         }
2318
2319         Ok(FnHeader { constness, unsafety, asyncness, ext })
2320     }
2321
2322     /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2323     fn ban_async_in_2015(&self, span: Span) {
2324         if span.rust_2015() {
2325             let diag = self.diagnostic();
2326             struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2327                 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2328                 .help_use_latest_edition()
2329                 .emit();
2330         }
2331     }
2332
2333     /// Parses the parameter list and result type of a function declaration.
2334     pub(super) fn parse_fn_decl(
2335         &mut self,
2336         req_name: ReqName,
2337         ret_allow_plus: AllowPlus,
2338         recover_return_sign: RecoverReturnSign,
2339     ) -> PResult<'a, P<FnDecl>> {
2340         Ok(P(FnDecl {
2341             inputs: self.parse_fn_params(req_name)?,
2342             output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2343         }))
2344     }
2345
2346     /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2347     fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2348         let mut first_param = true;
2349         // Parse the arguments, starting out with `self` being allowed...
2350         let (mut params, _) = self.parse_paren_comma_seq(|p| {
2351             let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2352                 e.emit();
2353                 let lo = p.prev_token.span;
2354                 // Skip every token until next possible arg or end.
2355                 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2356                 // Create a placeholder argument for proper arg count (issue #34264).
2357                 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2358             });
2359             // ...now that we've parsed the first argument, `self` is no longer allowed.
2360             first_param = false;
2361             param
2362         })?;
2363         // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2364         self.deduplicate_recovered_params_names(&mut params);
2365         Ok(params)
2366     }
2367
2368     /// Parses a single function parameter.
2369     ///
2370     /// - `self` is syntactically allowed when `first_param` holds.
2371     fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2372         let lo = self.token.span;
2373         let attrs = self.parse_outer_attributes()?;
2374         self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2375             // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2376             if let Some(mut param) = this.parse_self_param()? {
2377                 param.attrs = attrs;
2378                 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2379                 return Ok((res?, TrailingToken::None));
2380             }
2381
2382             let is_name_required = match this.token.kind {
2383                 token::DotDotDot => false,
2384                 _ => req_name(this.token.span.edition()),
2385             };
2386             let (pat, ty) = if is_name_required || this.is_named_param() {
2387                 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2388
2389                 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2390                 if !colon {
2391                     let mut err = this.unexpected::<()>().unwrap_err();
2392                     return if let Some(ident) =
2393                         this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2394                     {
2395                         err.emit();
2396                         Ok((dummy_arg(ident), TrailingToken::None))
2397                     } else {
2398                         Err(err)
2399                     };
2400                 }
2401
2402                 this.eat_incorrect_doc_comment_for_param_type();
2403                 (pat, this.parse_ty_for_param()?)
2404             } else {
2405                 debug!("parse_param_general ident_to_pat");
2406                 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2407                 this.eat_incorrect_doc_comment_for_param_type();
2408                 let mut ty = this.parse_ty_for_param();
2409                 if ty.is_ok()
2410                     && this.token != token::Comma
2411                     && this.token != token::CloseDelim(Delimiter::Parenthesis)
2412                 {
2413                     // This wasn't actually a type, but a pattern looking like a type,
2414                     // so we are going to rollback and re-parse for recovery.
2415                     ty = this.unexpected();
2416                 }
2417                 match ty {
2418                     Ok(ty) => {
2419                         let ident = Ident::new(kw::Empty, this.prev_token.span);
2420                         let bm = BindingAnnotation::NONE;
2421                         let pat = this.mk_pat_ident(ty.span, bm, ident);
2422                         (pat, ty)
2423                     }
2424                     // If this is a C-variadic argument and we hit an error, return the error.
2425                     Err(err) if this.token == token::DotDotDot => return Err(err),
2426                     // Recover from attempting to parse the argument as a type without pattern.
2427                     Err(err) => {
2428                         err.cancel();
2429                         this.restore_snapshot(parser_snapshot_before_ty);
2430                         this.recover_arg_parse()?
2431                     }
2432                 }
2433             };
2434
2435             let span = lo.to(this.prev_token.span);
2436
2437             Ok((
2438                 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2439                 TrailingToken::None,
2440             ))
2441         })
2442     }
2443
2444     /// Returns the parsed optional self parameter and whether a self shortcut was used.
2445     fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2446         // Extract an identifier *after* having confirmed that the token is one.
2447         let expect_self_ident = |this: &mut Self| match this.token.ident() {
2448             Some((ident, false)) => {
2449                 this.bump();
2450                 ident
2451             }
2452             _ => unreachable!(),
2453         };
2454         // Is `self` `n` tokens ahead?
2455         let is_isolated_self = |this: &Self, n| {
2456             this.is_keyword_ahead(n, &[kw::SelfLower])
2457                 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2458         };
2459         // Is `mut self` `n` tokens ahead?
2460         let is_isolated_mut_self =
2461             |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2462         // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2463         let parse_self_possibly_typed = |this: &mut Self, m| {
2464             let eself_ident = expect_self_ident(this);
2465             let eself_hi = this.prev_token.span;
2466             let eself = if this.eat(&token::Colon) {
2467                 SelfKind::Explicit(this.parse_ty()?, m)
2468             } else {
2469                 SelfKind::Value(m)
2470             };
2471             Ok((eself, eself_ident, eself_hi))
2472         };
2473         // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2474         let recover_self_ptr = |this: &mut Self| {
2475             let msg = "cannot pass `self` by raw pointer";
2476             let span = this.token.span;
2477             this.struct_span_err(span, msg).span_label(span, msg).emit();
2478
2479             Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2480         };
2481
2482         // Parse optional `self` parameter of a method.
2483         // Only a limited set of initial token sequences is considered `self` parameters; anything
2484         // else is parsed as a normal function parameter list, so some lookahead is required.
2485         let eself_lo = self.token.span;
2486         let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2487             token::BinOp(token::And) => {
2488                 let eself = if is_isolated_self(self, 1) {
2489                     // `&self`
2490                     self.bump();
2491                     SelfKind::Region(None, Mutability::Not)
2492                 } else if is_isolated_mut_self(self, 1) {
2493                     // `&mut self`
2494                     self.bump();
2495                     self.bump();
2496                     SelfKind::Region(None, Mutability::Mut)
2497                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2498                     // `&'lt self`
2499                     self.bump();
2500                     let lt = self.expect_lifetime();
2501                     SelfKind::Region(Some(lt), Mutability::Not)
2502                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2503                     // `&'lt mut self`
2504                     self.bump();
2505                     let lt = self.expect_lifetime();
2506                     self.bump();
2507                     SelfKind::Region(Some(lt), Mutability::Mut)
2508                 } else {
2509                     // `&not_self`
2510                     return Ok(None);
2511                 };
2512                 (eself, expect_self_ident(self), self.prev_token.span)
2513             }
2514             // `*self`
2515             token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2516                 self.bump();
2517                 recover_self_ptr(self)?
2518             }
2519             // `*mut self` and `*const self`
2520             token::BinOp(token::Star)
2521                 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2522             {
2523                 self.bump();
2524                 self.bump();
2525                 recover_self_ptr(self)?
2526             }
2527             // `self` and `self: TYPE`
2528             token::Ident(..) if is_isolated_self(self, 0) => {
2529                 parse_self_possibly_typed(self, Mutability::Not)?
2530             }
2531             // `mut self` and `mut self: TYPE`
2532             token::Ident(..) if is_isolated_mut_self(self, 0) => {
2533                 self.bump();
2534                 parse_self_possibly_typed(self, Mutability::Mut)?
2535             }
2536             _ => return Ok(None),
2537         };
2538
2539         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2540         Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2541     }
2542
2543     fn is_named_param(&self) -> bool {
2544         let offset = match self.token.kind {
2545             token::Interpolated(ref nt) => match **nt {
2546                 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2547                 _ => 0,
2548             },
2549             token::BinOp(token::And) | token::AndAnd => 1,
2550             _ if self.token.is_keyword(kw::Mut) => 1,
2551             _ => 0,
2552         };
2553
2554         self.look_ahead(offset, |t| t.is_ident())
2555             && self.look_ahead(offset + 1, |t| t == &token::Colon)
2556     }
2557
2558     fn recover_first_param(&mut self) -> &'static str {
2559         match self
2560             .parse_outer_attributes()
2561             .and_then(|_| self.parse_self_param())
2562             .map_err(|e| e.cancel())
2563         {
2564             Ok(Some(_)) => "method",
2565             _ => "function",
2566         }
2567     }
2568 }
2569
2570 enum IsMacroRulesItem {
2571     Yes { has_bang: bool },
2572     No,
2573 }