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