]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/item.rs
Auto merge of #69295 - ecstatic-morse:unified-dataflow-generators, r=tmandry
[rust.git] / src / librustc_parse / parser / item.rs
1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath};
3 use super::{FollowedByType, Parser, PathStyle};
4
5 use crate::maybe_whole;
6
7 use rustc_ast::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
8 use rustc_ast::ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind};
9 use rustc_ast::ast::{
10     Async, Const, Defaultness, IsAuto, PathSegment, Unsafe, UseTree, UseTreeKind,
11 };
12 use rustc_ast::ast::{
13     BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind,
14 };
15 use rustc_ast::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
16 use rustc_ast::ast::{FnHeader, ForeignItem, Mutability, Visibility, VisibilityKind};
17 use rustc_ast::ptr::P;
18 use rustc_ast::token;
19 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
20 use rustc_ast_pretty::pprust;
21 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
22 use rustc_span::edition::Edition;
23 use rustc_span::source_map::{self, Span};
24 use rustc_span::symbol::{kw, sym, Symbol};
25
26 use log::debug;
27 use std::mem;
28
29 pub(super) type ItemInfo = (Ident, ItemKind);
30
31 impl<'a> Parser<'a> {
32     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
33         self.parse_item_(|_| true).map(|i| i.map(P))
34     }
35
36     fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
37         let attrs = self.parse_outer_attributes()?;
38         self.parse_item_common(attrs, true, false, req_name)
39     }
40
41     pub(super) fn parse_item_common(
42         &mut self,
43         mut attrs: Vec<Attribute>,
44         mac_allowed: bool,
45         attrs_allowed: bool,
46         req_name: ReqName,
47     ) -> PResult<'a, Option<Item>> {
48         maybe_whole!(self, NtItem, |item| {
49             let mut item = item;
50             mem::swap(&mut item.attrs, &mut attrs);
51             item.attrs.extend(attrs);
52             Some(item.into_inner())
53         });
54
55         let mut unclosed_delims = vec![];
56         let (mut item, tokens) = self.collect_tokens(|this| {
57             let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
58             unclosed_delims.append(&mut this.unclosed_delims);
59             item
60         })?;
61         self.unclosed_delims.append(&mut unclosed_delims);
62
63         // Once we've parsed an item and recorded the tokens we got while
64         // parsing we may want to store `tokens` into the item we're about to
65         // return. Note, though, that we specifically didn't capture tokens
66         // related to outer attributes. The `tokens` field here may later be
67         // used with procedural macros to convert this item back into a token
68         // stream, but during expansion we may be removing attributes as we go
69         // along.
70         //
71         // If we've got inner attributes then the `tokens` we've got above holds
72         // these inner attributes. If an inner attribute is expanded we won't
73         // actually remove it from the token stream, so we'll just keep yielding
74         // it (bad!). To work around this case for now we just avoid recording
75         // `tokens` if we detect any inner attributes. This should help keep
76         // expansion correct, but we should fix this bug one day!
77         if let Some(item) = &mut item {
78             if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
79                 item.tokens = Some(tokens);
80             }
81         }
82         Ok(item)
83     }
84
85     fn parse_item_common_(
86         &mut self,
87         mut attrs: Vec<Attribute>,
88         mac_allowed: bool,
89         attrs_allowed: bool,
90         req_name: ReqName,
91     ) -> PResult<'a, Option<Item>> {
92         let lo = self.token.span;
93         let vis = self.parse_visibility(FollowedByType::No)?;
94         let mut def = self.parse_defaultness();
95         let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
96         if let Some((ident, kind)) = kind {
97             self.error_on_unconsumed_default(def, &kind);
98             let span = lo.to(self.prev_span);
99             let id = DUMMY_NODE_ID;
100             let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
101             return Ok(Some(item));
102         }
103
104         // At this point, we have failed to parse an item.
105         self.error_on_unmatched_vis(&vis);
106         self.error_on_unmatched_defaultness(def);
107         if !attrs_allowed {
108             self.recover_attrs_no_item(&attrs)?;
109         }
110         Ok(None)
111     }
112
113     /// Error in-case a non-inherited visibility was parsed but no item followed.
114     fn error_on_unmatched_vis(&self, vis: &Visibility) {
115         if let VisibilityKind::Inherited = vis.node {
116             return;
117         }
118         let vs = pprust::vis_to_string(&vis);
119         let vs = vs.trim_end();
120         self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
121             .span_label(vis.span, "the visibility")
122             .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
123             .emit();
124     }
125
126     /// Error in-case a `default` was parsed but no item followed.
127     fn error_on_unmatched_defaultness(&self, def: Defaultness) {
128         if let Defaultness::Default(sp) = def {
129             self.struct_span_err(sp, "`default` is not followed by an item")
130                 .span_label(sp, "the `default` qualifier")
131                 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
132                 .emit();
133         }
134     }
135
136     /// Error in-case `default` was parsed in an in-appropriate context.
137     fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
138         if let Defaultness::Default(span) = def {
139             let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
140             self.struct_span_err(span, &msg)
141                 .span_label(span, "`default` because of this")
142                 .note("only associated `fn`, `const`, and `type` items can be `default`")
143                 .emit();
144         }
145     }
146
147     /// Parses one of the items allowed by the flags.
148     fn parse_item_kind(
149         &mut self,
150         attrs: &mut Vec<Attribute>,
151         macros_allowed: bool,
152         lo: Span,
153         vis: &Visibility,
154         def: &mut Defaultness,
155         req_name: ReqName,
156     ) -> PResult<'a, Option<ItemInfo>> {
157         let mut def = || mem::replace(def, Defaultness::Final);
158
159         let info = if self.eat_keyword(kw::Use) {
160             // USE ITEM
161             let tree = self.parse_use_tree()?;
162             self.expect_semi()?;
163             (Ident::invalid(), ItemKind::Use(P(tree)))
164         } else if self.check_fn_front_matter() {
165             // FUNCTION ITEM
166             let (ident, sig, generics, body) = self.parse_fn(attrs, req_name)?;
167             (ident, ItemKind::Fn(def(), sig, generics, body))
168         } else if self.eat_keyword(kw::Extern) {
169             if self.eat_keyword(kw::Crate) {
170                 // EXTERN CRATE
171                 self.parse_item_extern_crate()?
172             } else {
173                 // EXTERN BLOCK
174                 self.parse_item_foreign_mod(attrs)?
175             }
176         } else if self.is_static_global() {
177             // STATIC ITEM
178             self.bump(); // `static`
179             let m = self.parse_mutability();
180             let (ident, ty, expr) = self.parse_item_global(Some(m))?;
181             (ident, ItemKind::Static(ty, m, expr))
182         } else if let Const::Yes(const_span) = self.parse_constness() {
183             // CONST ITEM
184             self.recover_const_mut(const_span);
185             let (ident, ty, expr) = self.parse_item_global(None)?;
186             (ident, ItemKind::Const(def(), ty, expr))
187         } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
188             // TRAIT ITEM
189             self.parse_item_trait(attrs, lo)?
190         } else if self.check_keyword(kw::Impl)
191             || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
192         {
193             // IMPL ITEM
194             self.parse_item_impl(attrs, def())?
195         } else if self.eat_keyword(kw::Mod) {
196             // MODULE ITEM
197             self.parse_item_mod(attrs)?
198         } else if self.eat_keyword(kw::Type) {
199             // TYPE ITEM
200             self.parse_type_alias(def())?
201         } else if self.eat_keyword(kw::Enum) {
202             // ENUM ITEM
203             self.parse_item_enum()?
204         } else if self.eat_keyword(kw::Struct) {
205             // STRUCT ITEM
206             self.parse_item_struct()?
207         } else if self.is_kw_followed_by_ident(kw::Union) {
208             // UNION ITEM
209             self.bump(); // `union`
210             self.parse_item_union()?
211         } else if self.eat_keyword(kw::Macro) {
212             // MACROS 2.0 ITEM
213             self.parse_item_decl_macro(lo)?
214         } else if self.is_macro_rules_item() {
215             // MACRO_RULES ITEM
216             self.parse_item_macro_rules(vis)?
217         } else if vis.node.is_pub() && self.isnt_macro_invocation() {
218             self.recover_missing_kw_before_item()?;
219             return Ok(None);
220         } else if macros_allowed && self.token.is_path_start() {
221             // MACRO INVOCATION ITEM
222             (Ident::invalid(), ItemKind::Mac(self.parse_item_macro(vis)?))
223         } else {
224             return Ok(None);
225         };
226         Ok(Some(info))
227     }
228
229     /// When parsing a statement, would the start of a path be an item?
230     pub(super) fn is_path_start_item(&mut self) -> bool {
231         self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
232         || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
233         || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
234         || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
235         || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
236     }
237
238     /// Are we sure this could not possibly be a macro invocation?
239     fn isnt_macro_invocation(&mut self) -> bool {
240         self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
241     }
242
243     /// Recover on encountering a struct or method definition where the user
244     /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
245     fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
246         // Space between `pub` keyword and the identifier
247         //
248         //     pub   S {}
249         //        ^^^ `sp` points here
250         let sp = self.prev_span.between(self.token.span);
251         let full_sp = self.prev_span.to(self.token.span);
252         let ident_sp = self.token.span;
253         if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
254             // possible public struct definition where `struct` was forgotten
255             let ident = self.parse_ident().unwrap();
256             let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
257             let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
258             err.span_suggestion_short(
259                 sp,
260                 &msg,
261                 " struct ".into(),
262                 Applicability::MaybeIncorrect, // speculative
263             );
264             return Err(err);
265         } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
266             let ident = self.parse_ident().unwrap();
267             self.bump(); // `(`
268             let kw_name = self.recover_first_param();
269             self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
270             let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
271                 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
272                 self.bump(); // `{`
273                 ("fn", kw_name, false)
274             } else if self.check(&token::OpenDelim(token::Brace)) {
275                 self.bump(); // `{`
276                 ("fn", kw_name, false)
277             } else if self.check(&token::Colon) {
278                 let kw = "struct";
279                 (kw, kw, false)
280             } else {
281                 ("fn` or `struct", "function or struct", true)
282             };
283
284             let msg = format!("missing `{}` for {} definition", kw, kw_name);
285             let mut err = self.struct_span_err(sp, &msg);
286             if !ambiguous {
287                 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
288                 let suggestion =
289                     format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
290                 err.span_suggestion_short(
291                     sp,
292                     &suggestion,
293                     format!(" {} ", kw),
294                     Applicability::MachineApplicable,
295                 );
296             } else {
297                 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
298                     err.span_suggestion(
299                         full_sp,
300                         "if you meant to call a macro, try",
301                         format!("{}!", snippet),
302                         // this is the `ambiguous` conditional branch
303                         Applicability::MaybeIncorrect,
304                     );
305                 } else {
306                     err.help(
307                         "if you meant to call a macro, remove the `pub` \
308                                   and add a trailing `!` after the identifier",
309                     );
310                 }
311             }
312             return Err(err);
313         } else if self.look_ahead(1, |t| *t == token::Lt) {
314             let ident = self.parse_ident().unwrap();
315             self.eat_to_tokens(&[&token::Gt]);
316             self.bump(); // `>`
317             let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
318                 ("fn", self.recover_first_param(), false)
319             } else if self.check(&token::OpenDelim(token::Brace)) {
320                 ("struct", "struct", false)
321             } else {
322                 ("fn` or `struct", "function or struct", true)
323             };
324             let msg = format!("missing `{}` for {} definition", kw, kw_name);
325             let mut err = self.struct_span_err(sp, &msg);
326             if !ambiguous {
327                 err.span_suggestion_short(
328                     sp,
329                     &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
330                     format!(" {} ", kw),
331                     Applicability::MachineApplicable,
332                 );
333             }
334             return Err(err);
335         } else {
336             Ok(())
337         }
338     }
339
340     /// Parses an item macro, e.g., `item!();`.
341     fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, Mac> {
342         let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
343         self.expect(&token::Not)?; // `!`
344         let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
345         self.eat_semi_for_macro_if_needed(&args);
346         self.complain_if_pub_macro(vis, false);
347         Ok(Mac { path, args, prior_type_ascription: self.last_type_ascription })
348     }
349
350     /// Recover if we parsed attributes and expected an item but there was none.
351     fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
352         let (start, end) = match attrs {
353             [] => return Ok(()),
354             [x0] => (x0, x0),
355             [x0, .., xn] => (x0, xn),
356         };
357         let msg = if end.is_doc_comment() {
358             "expected item after doc comment"
359         } else {
360             "expected item after attributes"
361         };
362         let mut err = self.struct_span_err(end.span, msg);
363         if end.is_doc_comment() {
364             err.span_label(end.span, "this doc comment doesn't document anything");
365         }
366         if let [.., penultimate, _] = attrs {
367             err.span_label(start.span.to(penultimate.span), "other attributes here");
368         }
369         Err(err)
370     }
371
372     fn is_async_fn(&self) -> bool {
373         self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
374     }
375
376     /// Parses an implementation item.
377     ///
378     /// ```
379     /// impl<'a, T> TYPE { /* impl items */ }
380     /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
381     /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
382     /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
383     /// ```
384     ///
385     /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
386     /// ```
387     /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
388     /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
389     /// ```
390     fn parse_item_impl(
391         &mut self,
392         attrs: &mut Vec<Attribute>,
393         defaultness: Defaultness,
394     ) -> PResult<'a, ItemInfo> {
395         let unsafety = self.parse_unsafety();
396         self.expect_keyword(kw::Impl)?;
397
398         // First, parse generic parameters if necessary.
399         let mut generics = if self.choose_generics_over_qpath() {
400             self.parse_generics()?
401         } else {
402             let mut generics = Generics::default();
403             // impl A for B {}
404             //    /\ this is where `generics.span` should point when there are no type params.
405             generics.span = self.prev_span.shrink_to_hi();
406             generics
407         };
408
409         let constness = self.parse_constness();
410         if let Const::Yes(span) = constness {
411             self.sess.gated_spans.gate(sym::const_trait_impl, span);
412         }
413
414         // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
415         let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
416             self.bump(); // `!`
417             ast::ImplPolarity::Negative
418         } else {
419             ast::ImplPolarity::Positive
420         };
421
422         // Parse both types and traits as a type, then reinterpret if necessary.
423         let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
424         let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
425         {
426             let span = self.prev_span.between(self.token.span);
427             self.struct_span_err(span, "missing trait in a trait impl").emit();
428             P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
429         } else {
430             self.parse_ty()?
431         };
432
433         // If `for` is missing we try to recover.
434         let has_for = self.eat_keyword(kw::For);
435         let missing_for_span = self.prev_span.between(self.token.span);
436
437         let ty_second = if self.token == token::DotDot {
438             // We need to report this error after `cfg` expansion for compatibility reasons
439             self.bump(); // `..`, do not add it to expected tokens
440             Some(self.mk_ty(self.prev_span, TyKind::Err))
441         } else if has_for || self.token.can_begin_type() {
442             Some(self.parse_ty()?)
443         } else {
444             None
445         };
446
447         generics.where_clause = self.parse_where_clause()?;
448
449         let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
450
451         let item_kind = match ty_second {
452             Some(ty_second) => {
453                 // impl Trait for Type
454                 if !has_for {
455                     self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
456                         .span_suggestion_short(
457                             missing_for_span,
458                             "add `for` here",
459                             " for ".to_string(),
460                             Applicability::MachineApplicable,
461                         )
462                         .emit();
463                 }
464
465                 let ty_first = ty_first.into_inner();
466                 let path = match ty_first.kind {
467                     // This notably includes paths passed through `ty` macro fragments (#46438).
468                     TyKind::Path(None, path) => path,
469                     _ => {
470                         self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
471                         err_path(ty_first.span)
472                     }
473                 };
474                 let trait_ref = TraitRef { path, ref_id: ty_first.id };
475
476                 ItemKind::Impl {
477                     unsafety,
478                     polarity,
479                     defaultness,
480                     constness,
481                     generics,
482                     of_trait: Some(trait_ref),
483                     self_ty: ty_second,
484                     items: impl_items,
485                 }
486             }
487             None => {
488                 // impl Type
489                 ItemKind::Impl {
490                     unsafety,
491                     polarity,
492                     defaultness,
493                     constness,
494                     generics,
495                     of_trait: None,
496                     self_ty: ty_first,
497                     items: impl_items,
498                 }
499             }
500         };
501
502         Ok((Ident::invalid(), item_kind))
503     }
504
505     fn parse_item_list<T>(
506         &mut self,
507         attrs: &mut Vec<Attribute>,
508         mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
509     ) -> PResult<'a, Vec<T>> {
510         let open_brace_span = self.token.span;
511         self.expect(&token::OpenDelim(token::Brace))?;
512         attrs.append(&mut self.parse_inner_attributes()?);
513
514         let mut items = Vec::new();
515         while !self.eat(&token::CloseDelim(token::Brace)) {
516             if self.recover_doc_comment_before_brace() {
517                 continue;
518             }
519             match parse_item(self) {
520                 Ok(None) => {
521                     // We have to bail or we'll potentially never make progress.
522                     let non_item_span = self.token.span;
523                     self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
524                     self.struct_span_err(non_item_span, "non-item in item list")
525                         .span_label(open_brace_span, "item list starts here")
526                         .span_label(non_item_span, "non-item starts here")
527                         .span_label(self.prev_span, "item list ends here")
528                         .emit();
529                     break;
530                 }
531                 Ok(Some(item)) => items.extend(item),
532                 Err(mut err) => {
533                     self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
534                     err.span_label(open_brace_span, "while parsing this item list starting here")
535                         .span_label(self.prev_span, "the item list ends here")
536                         .emit();
537                     break;
538                 }
539             }
540         }
541         Ok(items)
542     }
543
544     /// Recover on a doc comment before `}`.
545     fn recover_doc_comment_before_brace(&mut self) -> bool {
546         if let token::DocComment(_) = self.token.kind {
547             if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
548                 struct_span_err!(
549                     self.diagnostic(),
550                     self.token.span,
551                     E0584,
552                     "found a documentation comment that doesn't document anything",
553                 )
554                 .span_label(self.token.span, "this doc comment doesn't document anything")
555                 .help(
556                     "doc comments must come before what they document, maybe a \
557                     comment was intended with `//`?",
558                 )
559                 .emit();
560                 self.bump();
561                 return true;
562             }
563         }
564         false
565     }
566
567     /// Parses defaultness (i.e., `default` or nothing).
568     fn parse_defaultness(&mut self) -> Defaultness {
569         // We are interested in `default` followed by another identifier.
570         // However, we must avoid keywords that occur as binary operators.
571         // Currently, the only applicable keyword is `as` (`default as Ty`).
572         if self.check_keyword(kw::Default)
573             && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
574         {
575             self.bump(); // `default`
576             Defaultness::Default(self.prev_span)
577         } else {
578             Defaultness::Final
579         }
580     }
581
582     /// Is this an `(unsafe auto? | auto) trait` item?
583     fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
584         // auto trait
585         self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
586             // unsafe auto trait
587             || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
588     }
589
590     /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
591     fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
592         let unsafety = self.parse_unsafety();
593         // Parse optional `auto` prefix.
594         let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
595
596         self.expect_keyword(kw::Trait)?;
597         let ident = self.parse_ident()?;
598         let mut tps = self.parse_generics()?;
599
600         // Parse optional colon and supertrait bounds.
601         let had_colon = self.eat(&token::Colon);
602         let span_at_colon = self.prev_span;
603         let bounds =
604             if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
605
606         let span_before_eq = self.prev_span;
607         if self.eat(&token::Eq) {
608             // It's a trait alias.
609             if had_colon {
610                 let span = span_at_colon.to(span_before_eq);
611                 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
612             }
613
614             let bounds = self.parse_generic_bounds(None)?;
615             tps.where_clause = self.parse_where_clause()?;
616             self.expect_semi()?;
617
618             let whole_span = lo.to(self.prev_span);
619             if is_auto == IsAuto::Yes {
620                 let msg = "trait aliases cannot be `auto`";
621                 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
622             }
623             if let Unsafe::Yes(_) = unsafety {
624                 let msg = "trait aliases cannot be `unsafe`";
625                 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
626             }
627
628             self.sess.gated_spans.gate(sym::trait_alias, whole_span);
629
630             Ok((ident, ItemKind::TraitAlias(tps, bounds)))
631         } else {
632             // It's a normal trait.
633             tps.where_clause = self.parse_where_clause()?;
634             let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
635             Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
636         }
637     }
638
639     pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
640         self.parse_assoc_item(|_| true)
641     }
642
643     pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
644         self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
645     }
646
647     /// Parses associated items.
648     fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
649         Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
650             let kind = match kind {
651                 ItemKind::Mac(a) => AssocItemKind::Macro(a),
652                 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
653                 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
654                 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
655                 ItemKind::Static(a, _, b) => {
656                     self.struct_span_err(span, "associated `static` items are not allowed").emit();
657                     AssocItemKind::Const(Defaultness::Final, a, b)
658                 }
659                 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
660             };
661             Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
662         }))
663     }
664
665     /// Parses a `type` alias with the following grammar:
666     /// ```
667     /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
668     /// ```
669     /// The `"type"` has already been eaten.
670     fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
671         let ident = self.parse_ident()?;
672         let mut generics = self.parse_generics()?;
673
674         // Parse optional colon and param bounds.
675         let bounds =
676             if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
677         generics.where_clause = self.parse_where_clause()?;
678
679         let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
680         self.expect_semi()?;
681
682         Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
683     }
684
685     /// Parses a `UseTree`.
686     ///
687     /// ```
688     /// USE_TREE = [`::`] `*` |
689     ///            [`::`] `{` USE_TREE_LIST `}` |
690     ///            PATH `::` `*` |
691     ///            PATH `::` `{` USE_TREE_LIST `}` |
692     ///            PATH [`as` IDENT]
693     /// ```
694     fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
695         let lo = self.token.span;
696
697         let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
698         let kind = if self.check(&token::OpenDelim(token::Brace))
699             || self.check(&token::BinOp(token::Star))
700             || self.is_import_coupler()
701         {
702             // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
703             let mod_sep_ctxt = self.token.span.ctxt();
704             if self.eat(&token::ModSep) {
705                 prefix
706                     .segments
707                     .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
708             }
709
710             self.parse_use_tree_glob_or_nested()?
711         } else {
712             // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
713             prefix = self.parse_path(PathStyle::Mod)?;
714
715             if self.eat(&token::ModSep) {
716                 self.parse_use_tree_glob_or_nested()?
717             } else {
718                 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
719             }
720         };
721
722         Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
723     }
724
725     /// Parses `*` or `{...}`.
726     fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
727         Ok(if self.eat(&token::BinOp(token::Star)) {
728             UseTreeKind::Glob
729         } else {
730             UseTreeKind::Nested(self.parse_use_tree_list()?)
731         })
732     }
733
734     /// Parses a `UseTreeKind::Nested(list)`.
735     ///
736     /// ```
737     /// USE_TREE_LIST = Ã˜ | (USE_TREE `,`)* USE_TREE [`,`]
738     /// ```
739     fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
740         self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
741             .map(|(r, _)| r)
742     }
743
744     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
745         if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
746     }
747
748     fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
749         match self.normalized_token.kind {
750             token::Ident(name @ kw::Underscore, false) => {
751                 self.bump();
752                 Ok(Ident::new(name, self.normalized_prev_token.span))
753             }
754             _ => self.parse_ident(),
755         }
756     }
757
758     /// Parses `extern crate` links.
759     ///
760     /// # Examples
761     ///
762     /// ```
763     /// extern crate foo;
764     /// extern crate bar as foo;
765     /// ```
766     fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
767         // Accept `extern crate name-like-this` for better diagnostics
768         let orig_name = self.parse_crate_name_with_dashes()?;
769         let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
770             (rename, Some(orig_name.name))
771         } else {
772             (orig_name, None)
773         };
774         self.expect_semi()?;
775         Ok((item_name, ItemKind::ExternCrate(orig_name)))
776     }
777
778     fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
779         let error_msg = "crate name using dashes are not valid in `extern crate` statements";
780         let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
781                               in the code";
782         let mut ident = if self.token.is_keyword(kw::SelfLower) {
783             self.parse_path_segment_ident()
784         } else {
785             self.parse_ident()
786         }?;
787         let mut idents = vec![];
788         let mut replacement = vec![];
789         let mut fixed_crate_name = false;
790         // Accept `extern crate name-like-this` for better diagnostics.
791         let dash = token::BinOp(token::BinOpToken::Minus);
792         if self.token == dash {
793             // Do not include `-` as part of the expected tokens list.
794             while self.eat(&dash) {
795                 fixed_crate_name = true;
796                 replacement.push((self.prev_span, "_".to_string()));
797                 idents.push(self.parse_ident()?);
798             }
799         }
800         if fixed_crate_name {
801             let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
802             let mut fixed_name = format!("{}", ident.name);
803             for part in idents {
804                 fixed_name.push_str(&format!("_{}", part.name));
805             }
806             ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
807
808             self.struct_span_err(fixed_name_sp, error_msg)
809                 .span_label(fixed_name_sp, "dash-separated idents are not valid")
810                 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
811                 .emit();
812         }
813         Ok(ident)
814     }
815
816     /// Parses `extern` for foreign ABIs modules.
817     ///
818     /// `extern` is expected to have been consumed before calling this method.
819     ///
820     /// # Examples
821     ///
822     /// ```ignore (only-for-syntax-highlight)
823     /// extern "C" {}
824     /// extern {}
825     /// ```
826     fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
827         let abi = self.parse_abi(); // ABI?
828         let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
829         let module = ast::ForeignMod { abi, items };
830         Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
831     }
832
833     /// Parses a foreign item (one in an `extern { ... }` block).
834     pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
835         Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
836             let kind = match kind {
837                 ItemKind::Mac(a) => ForeignItemKind::Macro(a),
838                 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
839                 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
840                 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
841                 ItemKind::Const(_, a, b) => {
842                     self.error_on_foreign_const(span, ident);
843                     ForeignItemKind::Static(a, Mutability::Not, b)
844                 }
845                 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
846             };
847             Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
848         }))
849     }
850
851     fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
852         let span = self.sess.source_map().def_span(span);
853         let msg = format!("{} is not supported in {}", kind.descr(), ctx);
854         self.struct_span_err(span, &msg).emit();
855         return None;
856     }
857
858     fn error_on_foreign_const(&self, span: Span, ident: Ident) {
859         self.struct_span_err(ident.span, "extern items cannot be `const`")
860             .span_suggestion(
861                 span.with_hi(ident.span.lo()),
862                 "try using a static value",
863                 "static ".to_string(),
864                 Applicability::MachineApplicable,
865             )
866             .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
867             .emit();
868     }
869
870     fn is_static_global(&mut self) -> bool {
871         if self.check_keyword(kw::Static) {
872             // Check if this could be a closure.
873             !self.look_ahead(1, |token| {
874                 if token.is_keyword(kw::Move) {
875                     return true;
876                 }
877                 match token.kind {
878                     token::BinOp(token::Or) | token::OrOr => true,
879                     _ => false,
880                 }
881             })
882         } else {
883             false
884         }
885     }
886
887     /// Recover on `const mut` with `const` already eaten.
888     fn recover_const_mut(&mut self, const_span: Span) {
889         if self.eat_keyword(kw::Mut) {
890             let span = self.prev_span;
891             self.struct_span_err(span, "const globals cannot be mutable")
892                 .span_label(span, "cannot be mutable")
893                 .span_suggestion(
894                     const_span,
895                     "you might want to declare a static instead",
896                     "static".to_owned(),
897                     Applicability::MaybeIncorrect,
898                 )
899                 .emit();
900         }
901     }
902
903     /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
904     /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
905     ///
906     /// When `m` is `"const"`, `$ident` may also be `"_"`.
907     fn parse_item_global(
908         &mut self,
909         m: Option<Mutability>,
910     ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
911         let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
912
913         // Parse the type of a `const` or `static mut?` item.
914         // That is, the `":" $ty` fragment.
915         let ty = if self.eat(&token::Colon) {
916             self.parse_ty()?
917         } else {
918             self.recover_missing_const_type(id, m)
919         };
920
921         let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
922         self.expect_semi()?;
923         Ok((id, ty, expr))
924     }
925
926     /// We were supposed to parse `:` but the `:` was missing.
927     /// This means that the type is missing.
928     fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
929         // Construct the error and stash it away with the hope
930         // that typeck will later enrich the error with a type.
931         let kind = match m {
932             Some(Mutability::Mut) => "static mut",
933             Some(Mutability::Not) => "static",
934             None => "const",
935         };
936         let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
937         err.span_suggestion(
938             id.span,
939             "provide a type for the item",
940             format!("{}: <type>", id),
941             Applicability::HasPlaceholders,
942         );
943         err.stash(id.span, StashKey::ItemNoType);
944
945         // The user intended that the type be inferred,
946         // so treat this as if the user wrote e.g. `const A: _ = expr;`.
947         P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
948     }
949
950     /// Parses an enum declaration.
951     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
952         let id = self.parse_ident()?;
953         let mut generics = self.parse_generics()?;
954         generics.where_clause = self.parse_where_clause()?;
955
956         let (variants, _) =
957             self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
958                 self.recover_stmt();
959                 e
960             })?;
961
962         let enum_definition =
963             EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
964         Ok((id, ItemKind::Enum(enum_definition, generics)))
965     }
966
967     fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
968         let variant_attrs = self.parse_outer_attributes()?;
969         let vlo = self.token.span;
970
971         let vis = self.parse_visibility(FollowedByType::No)?;
972         if !self.recover_nested_adt_item(kw::Enum)? {
973             return Ok(None);
974         }
975         let ident = self.parse_ident()?;
976
977         let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
978             // Parse a struct variant.
979             let (fields, recovered) = self.parse_record_struct_body()?;
980             VariantData::Struct(fields, recovered)
981         } else if self.check(&token::OpenDelim(token::Paren)) {
982             VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
983         } else {
984             VariantData::Unit(DUMMY_NODE_ID)
985         };
986
987         let disr_expr =
988             if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
989
990         let vr = ast::Variant {
991             ident,
992             vis,
993             id: DUMMY_NODE_ID,
994             attrs: variant_attrs,
995             data: struct_def,
996             disr_expr,
997             span: vlo.to(self.prev_span),
998             is_placeholder: false,
999         };
1000
1001         Ok(Some(vr))
1002     }
1003
1004     /// Parses `struct Foo { ... }`.
1005     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1006         let class_name = self.parse_ident()?;
1007
1008         let mut generics = self.parse_generics()?;
1009
1010         // There is a special case worth noting here, as reported in issue #17904.
1011         // If we are parsing a tuple struct it is the case that the where clause
1012         // should follow the field list. Like so:
1013         //
1014         // struct Foo<T>(T) where T: Copy;
1015         //
1016         // If we are parsing a normal record-style struct it is the case
1017         // that the where clause comes before the body, and after the generics.
1018         // So if we look ahead and see a brace or a where-clause we begin
1019         // parsing a record style struct.
1020         //
1021         // Otherwise if we look ahead and see a paren we parse a tuple-style
1022         // struct.
1023
1024         let vdata = if self.token.is_keyword(kw::Where) {
1025             generics.where_clause = self.parse_where_clause()?;
1026             if self.eat(&token::Semi) {
1027                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1028                 VariantData::Unit(DUMMY_NODE_ID)
1029             } else {
1030                 // If we see: `struct Foo<T> where T: Copy { ... }`
1031                 let (fields, recovered) = self.parse_record_struct_body()?;
1032                 VariantData::Struct(fields, recovered)
1033             }
1034         // No `where` so: `struct Foo<T>;`
1035         } else if self.eat(&token::Semi) {
1036             VariantData::Unit(DUMMY_NODE_ID)
1037         // Record-style struct definition
1038         } else if self.token == token::OpenDelim(token::Brace) {
1039             let (fields, recovered) = self.parse_record_struct_body()?;
1040             VariantData::Struct(fields, recovered)
1041         // Tuple-style struct definition with optional where-clause.
1042         } else if self.token == token::OpenDelim(token::Paren) {
1043             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1044             generics.where_clause = self.parse_where_clause()?;
1045             self.expect_semi()?;
1046             body
1047         } else {
1048             let token_str = super::token_descr(&self.token);
1049             let msg = &format!(
1050                 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1051                 token_str
1052             );
1053             let mut err = self.struct_span_err(self.token.span, msg);
1054             err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1055             return Err(err);
1056         };
1057
1058         Ok((class_name, ItemKind::Struct(vdata, generics)))
1059     }
1060
1061     /// Parses `union Foo { ... }`.
1062     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1063         let class_name = self.parse_ident()?;
1064
1065         let mut generics = self.parse_generics()?;
1066
1067         let vdata = if self.token.is_keyword(kw::Where) {
1068             generics.where_clause = self.parse_where_clause()?;
1069             let (fields, recovered) = self.parse_record_struct_body()?;
1070             VariantData::Struct(fields, recovered)
1071         } else if self.token == token::OpenDelim(token::Brace) {
1072             let (fields, recovered) = self.parse_record_struct_body()?;
1073             VariantData::Struct(fields, recovered)
1074         } else {
1075             let token_str = super::token_descr(&self.token);
1076             let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1077             let mut err = self.struct_span_err(self.token.span, msg);
1078             err.span_label(self.token.span, "expected `where` or `{` after union name");
1079             return Err(err);
1080         };
1081
1082         Ok((class_name, ItemKind::Union(vdata, generics)))
1083     }
1084
1085     fn parse_record_struct_body(
1086         &mut self,
1087     ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1088         let mut fields = Vec::new();
1089         let mut recovered = false;
1090         if self.eat(&token::OpenDelim(token::Brace)) {
1091             while self.token != token::CloseDelim(token::Brace) {
1092                 let field = self.parse_struct_decl_field().map_err(|e| {
1093                     self.consume_block(token::Brace, ConsumeClosingDelim::No);
1094                     recovered = true;
1095                     e
1096                 });
1097                 match field {
1098                     Ok(field) => fields.push(field),
1099                     Err(mut err) => {
1100                         err.emit();
1101                         break;
1102                     }
1103                 }
1104             }
1105             self.eat(&token::CloseDelim(token::Brace));
1106         } else {
1107             let token_str = super::token_descr(&self.token);
1108             let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1109             let mut err = self.struct_span_err(self.token.span, msg);
1110             err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1111             return Err(err);
1112         }
1113
1114         Ok((fields, recovered))
1115     }
1116
1117     fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1118         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1119         // Unit like structs are handled in parse_item_struct function
1120         self.parse_paren_comma_seq(|p| {
1121             let attrs = p.parse_outer_attributes()?;
1122             let lo = p.token.span;
1123             let vis = p.parse_visibility(FollowedByType::Yes)?;
1124             let ty = p.parse_ty()?;
1125             Ok(StructField {
1126                 span: lo.to(ty.span),
1127                 vis,
1128                 ident: None,
1129                 id: DUMMY_NODE_ID,
1130                 ty,
1131                 attrs,
1132                 is_placeholder: false,
1133             })
1134         })
1135         .map(|(r, _)| r)
1136     }
1137
1138     /// Parses an element of a struct declaration.
1139     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1140         let attrs = self.parse_outer_attributes()?;
1141         let lo = self.token.span;
1142         let vis = self.parse_visibility(FollowedByType::No)?;
1143         self.parse_single_struct_field(lo, vis, attrs)
1144     }
1145
1146     /// Parses a structure field declaration.
1147     fn parse_single_struct_field(
1148         &mut self,
1149         lo: Span,
1150         vis: Visibility,
1151         attrs: Vec<Attribute>,
1152     ) -> PResult<'a, StructField> {
1153         let mut seen_comma: bool = false;
1154         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1155         if self.token == token::Comma {
1156             seen_comma = true;
1157         }
1158         match self.token.kind {
1159             token::Comma => {
1160                 self.bump();
1161             }
1162             token::CloseDelim(token::Brace) => {}
1163             token::DocComment(_) => {
1164                 let previous_span = self.prev_span;
1165                 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1166                 self.bump(); // consume the doc comment
1167                 let comma_after_doc_seen = self.eat(&token::Comma);
1168                 // `seen_comma` is always false, because we are inside doc block
1169                 // condition is here to make code more readable
1170                 if !seen_comma && comma_after_doc_seen {
1171                     seen_comma = true;
1172                 }
1173                 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1174                     err.emit();
1175                 } else {
1176                     if !seen_comma {
1177                         let sp = self.sess.source_map().next_point(previous_span);
1178                         err.span_suggestion(
1179                             sp,
1180                             "missing comma here",
1181                             ",".into(),
1182                             Applicability::MachineApplicable,
1183                         );
1184                     }
1185                     return Err(err);
1186                 }
1187             }
1188             _ => {
1189                 let sp = self.prev_span.shrink_to_hi();
1190                 let mut err = self.struct_span_err(
1191                     sp,
1192                     &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1193                 );
1194                 if self.token.is_ident() {
1195                     // This is likely another field; emit the diagnostic and keep going
1196                     err.span_suggestion(
1197                         sp,
1198                         "try adding a comma",
1199                         ",".into(),
1200                         Applicability::MachineApplicable,
1201                     );
1202                     err.emit();
1203                 } else {
1204                     return Err(err);
1205                 }
1206             }
1207         }
1208         Ok(a_var)
1209     }
1210
1211     /// Parses a structure field.
1212     fn parse_name_and_ty(
1213         &mut self,
1214         lo: Span,
1215         vis: Visibility,
1216         attrs: Vec<Attribute>,
1217     ) -> PResult<'a, StructField> {
1218         let name = self.parse_ident()?;
1219         self.expect(&token::Colon)?;
1220         let ty = self.parse_ty()?;
1221         Ok(StructField {
1222             span: lo.to(self.prev_span),
1223             ident: Some(name),
1224             vis,
1225             id: DUMMY_NODE_ID,
1226             ty,
1227             attrs,
1228             is_placeholder: false,
1229         })
1230     }
1231
1232     /// Parses a declarative macro 2.0 definition.
1233     /// The `macro` keyword has already been parsed.
1234     /// ```
1235     /// MacBody = "{" TOKEN_STREAM "}" ;
1236     /// MacParams = "(" TOKEN_STREAM ")" ;
1237     /// DeclMac = "macro" Ident MacParams? MacBody ;
1238     /// ```
1239     fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1240         let ident = self.parse_ident()?;
1241         let body = if self.check(&token::OpenDelim(token::Brace)) {
1242             self.parse_mac_args()? // `MacBody`
1243         } else if self.check(&token::OpenDelim(token::Paren)) {
1244             let params = self.parse_token_tree(); // `MacParams`
1245             let pspan = params.span();
1246             if !self.check(&token::OpenDelim(token::Brace)) {
1247                 return self.unexpected();
1248             }
1249             let body = self.parse_token_tree(); // `MacBody`
1250             // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1251             let bspan = body.span();
1252             let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1253             let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1254             let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1255             P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1256         } else {
1257             return self.unexpected();
1258         };
1259
1260         self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1261         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1262     }
1263
1264     /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1265     fn is_macro_rules_item(&mut self) -> bool {
1266         self.check_keyword(kw::MacroRules)
1267             && self.look_ahead(1, |t| *t == token::Not)
1268             && self.look_ahead(2, |t| t.is_ident())
1269     }
1270
1271     /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1272     fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1273         self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1274         self.expect(&token::Not)?; // `!`
1275
1276         let ident = self.parse_ident()?;
1277         let body = self.parse_mac_args()?;
1278         self.eat_semi_for_macro_if_needed(&body);
1279         self.complain_if_pub_macro(vis, true);
1280
1281         Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1282     }
1283
1284     /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1285     /// If that's not the case, emit an error.
1286     fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1287         if let VisibilityKind::Inherited = vis.node {
1288             return;
1289         }
1290
1291         let vstr = pprust::vis_to_string(vis);
1292         let vstr = vstr.trim_end();
1293         if macro_rules {
1294             let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1295             self.struct_span_err(vis.span, &msg)
1296                 .span_suggestion(
1297                     vis.span,
1298                     "try exporting the macro",
1299                     "#[macro_export]".to_owned(),
1300                     Applicability::MaybeIncorrect, // speculative
1301                 )
1302                 .emit();
1303         } else {
1304             self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1305                 .span_suggestion(
1306                     vis.span,
1307                     "remove the visibility",
1308                     String::new(),
1309                     Applicability::MachineApplicable,
1310                 )
1311                 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1312                 .emit();
1313         }
1314     }
1315
1316     fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1317         if args.need_semicolon() && !self.eat(&token::Semi) {
1318             self.report_invalid_macro_expansion_item(args);
1319         }
1320     }
1321
1322     fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1323         let span = args.span().expect("undelimited macro call");
1324         let mut err = self.struct_span_err(
1325             span,
1326             "macros that expand to items must be delimited with braces or followed by a semicolon",
1327         );
1328         if self.unclosed_delims.is_empty() {
1329             let DelimSpan { open, close } = match args {
1330                 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1331                 MacArgs::Delimited(dspan, ..) => *dspan,
1332             };
1333             err.multipart_suggestion(
1334                 "change the delimiters to curly braces",
1335                 vec![(open, "{".to_string()), (close, '}'.to_string())],
1336                 Applicability::MaybeIncorrect,
1337             );
1338         } else {
1339             err.span_suggestion(
1340                 span,
1341                 "change the delimiters to curly braces",
1342                 " { /* items */ }".to_string(),
1343                 Applicability::HasPlaceholders,
1344             );
1345         }
1346         err.span_suggestion(
1347             span.shrink_to_hi(),
1348             "add a semicolon",
1349             ';'.to_string(),
1350             Applicability::MaybeIncorrect,
1351         );
1352         err.emit();
1353     }
1354
1355     /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1356     /// it is, we try to parse the item and report error about nested types.
1357     fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1358         if (self.token.is_keyword(kw::Enum)
1359             || self.token.is_keyword(kw::Struct)
1360             || self.token.is_keyword(kw::Union))
1361             && self.look_ahead(1, |t| t.is_ident())
1362         {
1363             let kw_token = self.token.clone();
1364             let kw_str = pprust::token_to_string(&kw_token);
1365             let item = self.parse_item()?;
1366
1367             self.struct_span_err(
1368                 kw_token.span,
1369                 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1370             )
1371             .span_suggestion(
1372                 item.unwrap().span,
1373                 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1374                 String::new(),
1375                 Applicability::MaybeIncorrect,
1376             )
1377             .emit();
1378             // We successfully parsed the item but we must inform the caller about nested problem.
1379             return Ok(false);
1380         }
1381         Ok(true)
1382     }
1383 }
1384
1385 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1386 ///
1387 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1388 type ReqName = fn(Edition) -> bool;
1389
1390 /// Parsing of functions and methods.
1391 impl<'a> Parser<'a> {
1392     /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1393     fn parse_fn(
1394         &mut self,
1395         attrs: &mut Vec<Attribute>,
1396         req_name: ReqName,
1397     ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1398         let header = self.parse_fn_front_matter()?; // `const ... fn`
1399         let ident = self.parse_ident()?; // `foo`
1400         let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1401         let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1402         generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1403         let body = self.parse_fn_body(attrs)?; // `;` or `{ ... }`.
1404         Ok((ident, FnSig { header, decl }, generics, body))
1405     }
1406
1407     /// Parse the "body" of a function.
1408     /// This can either be `;` when there's no body,
1409     /// or e.g. a block when the function is a provided one.
1410     fn parse_fn_body(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, Option<P<Block>>> {
1411         let (inner_attrs, body) = match self.token.kind {
1412             token::Semi => {
1413                 self.bump();
1414                 (Vec::new(), None)
1415             }
1416             token::OpenDelim(token::Brace) => {
1417                 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1418                 (attrs, Some(body))
1419             }
1420             token::Interpolated(ref nt) => match **nt {
1421                 token::NtBlock(..) => {
1422                     let (attrs, body) = self.parse_inner_attrs_and_block()?;
1423                     (attrs, Some(body))
1424                 }
1425                 _ => return self.expected_semi_or_open_brace(),
1426             },
1427             _ => return self.expected_semi_or_open_brace(),
1428         };
1429         attrs.extend(inner_attrs);
1430         Ok(body)
1431     }
1432
1433     /// Is the current token the start of an `FnHeader` / not a valid parse?
1434     fn check_fn_front_matter(&mut self) -> bool {
1435         // We use an over-approximation here.
1436         // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1437         const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1438         self.check_keyword(kw::Fn) // Definitely an `fn`.
1439             // `$qual fn` or `$qual $qual`:
1440             || QUALS.iter().any(|&kw| self.check_keyword(kw))
1441                 && self.look_ahead(1, |t| {
1442                     // ...qualified and then `fn`, e.g. `const fn`.
1443                     t.is_keyword(kw::Fn)
1444                     // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1445                     || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1446                 })
1447             // `extern ABI fn`
1448             || self.check_keyword(kw::Extern)
1449                 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1450                 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1451     }
1452
1453     /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1454     /// up to and including the `fn` keyword. The formal grammar is:
1455     ///
1456     /// ```
1457     /// Extern = "extern" StringLit ;
1458     /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1459     /// FnFrontMatter = FnQual? "fn" ;
1460     /// ```
1461     fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1462         let constness = self.parse_constness();
1463         let asyncness = self.parse_asyncness();
1464         let unsafety = self.parse_unsafety();
1465         let ext = self.parse_extern()?;
1466
1467         if let Async::Yes { span, .. } = asyncness {
1468             self.ban_async_in_2015(span);
1469         }
1470
1471         if !self.eat_keyword(kw::Fn) {
1472             // It is possible for `expect_one_of` to recover given the contents of
1473             // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1474             // account for this.
1475             if !self.expect_one_of(&[], &[])? {
1476                 unreachable!()
1477             }
1478         }
1479
1480         Ok(FnHeader { constness, unsafety, asyncness, ext })
1481     }
1482
1483     /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1484     fn ban_async_in_2015(&self, span: Span) {
1485         if span.rust_2015() {
1486             let diag = self.diagnostic();
1487             struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1488                 .note("to use `async fn`, switch to Rust 2018")
1489                 .help("set `edition = \"2018\"` in `Cargo.toml`")
1490                 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1491                 .emit();
1492         }
1493     }
1494
1495     /// Parses the parameter list and result type of a function declaration.
1496     pub(super) fn parse_fn_decl(
1497         &mut self,
1498         req_name: ReqName,
1499         ret_allow_plus: AllowPlus,
1500     ) -> PResult<'a, P<FnDecl>> {
1501         Ok(P(FnDecl {
1502             inputs: self.parse_fn_params(req_name)?,
1503             output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1504         }))
1505     }
1506
1507     /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1508     fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1509         let mut first_param = true;
1510         // Parse the arguments, starting out with `self` being allowed...
1511         let (mut params, _) = self.parse_paren_comma_seq(|p| {
1512             let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1513                 e.emit();
1514                 let lo = p.prev_span;
1515                 // Skip every token until next possible arg or end.
1516                 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1517                 // Create a placeholder argument for proper arg count (issue #34264).
1518                 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1519             });
1520             // ...now that we've parsed the first argument, `self` is no longer allowed.
1521             first_param = false;
1522             param
1523         })?;
1524         // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1525         self.deduplicate_recovered_params_names(&mut params);
1526         Ok(params)
1527     }
1528
1529     /// Parses a single function parameter.
1530     ///
1531     /// - `self` is syntactically allowed when `first_param` holds.
1532     fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1533         let lo = self.token.span;
1534         let attrs = self.parse_outer_attributes()?;
1535
1536         // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1537         if let Some(mut param) = self.parse_self_param()? {
1538             param.attrs = attrs.into();
1539             return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1540         }
1541
1542         let is_name_required = match self.token.kind {
1543             token::DotDotDot => false,
1544             _ => req_name(self.normalized_token.span.edition()),
1545         };
1546         let (pat, ty) = if is_name_required || self.is_named_param() {
1547             debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1548
1549             let pat = self.parse_fn_param_pat()?;
1550             if let Err(mut err) = self.expect(&token::Colon) {
1551                 return if let Some(ident) =
1552                     self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1553                 {
1554                     err.emit();
1555                     Ok(dummy_arg(ident))
1556                 } else {
1557                     Err(err)
1558                 };
1559             }
1560
1561             self.eat_incorrect_doc_comment_for_param_type();
1562             (pat, self.parse_ty_for_param()?)
1563         } else {
1564             debug!("parse_param_general ident_to_pat");
1565             let parser_snapshot_before_ty = self.clone();
1566             self.eat_incorrect_doc_comment_for_param_type();
1567             let mut ty = self.parse_ty_for_param();
1568             if ty.is_ok()
1569                 && self.token != token::Comma
1570                 && self.token != token::CloseDelim(token::Paren)
1571             {
1572                 // This wasn't actually a type, but a pattern looking like a type,
1573                 // so we are going to rollback and re-parse for recovery.
1574                 ty = self.unexpected();
1575             }
1576             match ty {
1577                 Ok(ty) => {
1578                     let ident = Ident::new(kw::Invalid, self.prev_span);
1579                     let bm = BindingMode::ByValue(Mutability::Not);
1580                     let pat = self.mk_pat_ident(ty.span, bm, ident);
1581                     (pat, ty)
1582                 }
1583                 // If this is a C-variadic argument and we hit an error, return the error.
1584                 Err(err) if self.token == token::DotDotDot => return Err(err),
1585                 // Recover from attempting to parse the argument as a type without pattern.
1586                 Err(mut err) => {
1587                     err.cancel();
1588                     mem::replace(self, parser_snapshot_before_ty);
1589                     self.recover_arg_parse()?
1590                 }
1591             }
1592         };
1593
1594         let span = lo.to(self.token.span);
1595
1596         Ok(Param {
1597             attrs: attrs.into(),
1598             id: ast::DUMMY_NODE_ID,
1599             is_placeholder: false,
1600             pat,
1601             span,
1602             ty,
1603         })
1604     }
1605
1606     /// Returns the parsed optional self parameter and whether a self shortcut was used.
1607     fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1608         // Extract an identifier *after* having confirmed that the token is one.
1609         let expect_self_ident = |this: &mut Self| {
1610             match this.normalized_token.kind {
1611                 // Preserve hygienic context.
1612                 token::Ident(name, _) => {
1613                     this.bump();
1614                     Ident::new(name, this.normalized_prev_token.span)
1615                 }
1616                 _ => unreachable!(),
1617             }
1618         };
1619         // Is `self` `n` tokens ahead?
1620         let is_isolated_self = |this: &Self, n| {
1621             this.is_keyword_ahead(n, &[kw::SelfLower])
1622                 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1623         };
1624         // Is `mut self` `n` tokens ahead?
1625         let is_isolated_mut_self =
1626             |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1627         // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1628         let parse_self_possibly_typed = |this: &mut Self, m| {
1629             let eself_ident = expect_self_ident(this);
1630             let eself_hi = this.prev_span;
1631             let eself = if this.eat(&token::Colon) {
1632                 SelfKind::Explicit(this.parse_ty()?, m)
1633             } else {
1634                 SelfKind::Value(m)
1635             };
1636             Ok((eself, eself_ident, eself_hi))
1637         };
1638         // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1639         let recover_self_ptr = |this: &mut Self| {
1640             let msg = "cannot pass `self` by raw pointer";
1641             let span = this.token.span;
1642             this.struct_span_err(span, msg).span_label(span, msg).emit();
1643
1644             Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1645         };
1646
1647         // Parse optional `self` parameter of a method.
1648         // Only a limited set of initial token sequences is considered `self` parameters; anything
1649         // else is parsed as a normal function parameter list, so some lookahead is required.
1650         let eself_lo = self.token.span;
1651         let (eself, eself_ident, eself_hi) = match self.normalized_token.kind {
1652             token::BinOp(token::And) => {
1653                 let eself = if is_isolated_self(self, 1) {
1654                     // `&self`
1655                     self.bump();
1656                     SelfKind::Region(None, Mutability::Not)
1657                 } else if is_isolated_mut_self(self, 1) {
1658                     // `&mut self`
1659                     self.bump();
1660                     self.bump();
1661                     SelfKind::Region(None, Mutability::Mut)
1662                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1663                     // `&'lt self`
1664                     self.bump();
1665                     let lt = self.expect_lifetime();
1666                     SelfKind::Region(Some(lt), Mutability::Not)
1667                 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1668                     // `&'lt mut self`
1669                     self.bump();
1670                     let lt = self.expect_lifetime();
1671                     self.bump();
1672                     SelfKind::Region(Some(lt), Mutability::Mut)
1673                 } else {
1674                     // `&not_self`
1675                     return Ok(None);
1676                 };
1677                 (eself, expect_self_ident(self), self.prev_span)
1678             }
1679             // `*self`
1680             token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1681                 self.bump();
1682                 recover_self_ptr(self)?
1683             }
1684             // `*mut self` and `*const self`
1685             token::BinOp(token::Star)
1686                 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1687             {
1688                 self.bump();
1689                 self.bump();
1690                 recover_self_ptr(self)?
1691             }
1692             // `self` and `self: TYPE`
1693             token::Ident(..) if is_isolated_self(self, 0) => {
1694                 parse_self_possibly_typed(self, Mutability::Not)?
1695             }
1696             // `mut self` and `mut self: TYPE`
1697             token::Ident(..) if is_isolated_mut_self(self, 0) => {
1698                 self.bump();
1699                 parse_self_possibly_typed(self, Mutability::Mut)?
1700             }
1701             _ => return Ok(None),
1702         };
1703
1704         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1705         Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1706     }
1707
1708     fn is_named_param(&self) -> bool {
1709         let offset = match self.token.kind {
1710             token::Interpolated(ref nt) => match **nt {
1711                 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1712                 _ => 0,
1713             },
1714             token::BinOp(token::And) | token::AndAnd => 1,
1715             _ if self.token.is_keyword(kw::Mut) => 1,
1716             _ => 0,
1717         };
1718
1719         self.look_ahead(offset, |t| t.is_ident())
1720             && self.look_ahead(offset + 1, |t| t == &token::Colon)
1721     }
1722
1723     fn recover_first_param(&mut self) -> &'static str {
1724         match self
1725             .parse_outer_attributes()
1726             .and_then(|_| self.parse_self_param())
1727             .map_err(|mut e| e.cancel())
1728         {
1729             Ok(Some(_)) => "method",
1730             _ => "function",
1731         }
1732     }
1733 }