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