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