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