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