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