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