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