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