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