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