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