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