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