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