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