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