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