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