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