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