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