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