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