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