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