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