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