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