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