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