1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::{FollowedByType, Parser, PathStyle};
4 use crate::maybe_whole;
6 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, PResult, StashKey};
7 use rustc_span::source_map::{self, respan, Span};
8 use rustc_span::symbol::{kw, sym, Symbol};
9 use rustc_span::BytePos;
10 use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
11 use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind};
12 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
13 use syntax::ast::{Constness, Defaultness, Extern, IsAsync, IsAuto, PathSegment, StrLit, Unsafety};
14 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
15 use syntax::ast::{FnHeader, ForeignItem, ForeignItemKind, Mutability, Visibility, VisibilityKind};
16 use syntax::print::pprust;
19 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
24 pub(super) type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
27 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
28 let attrs = self.parse_outer_attributes()?;
29 self.parse_item_(attrs, true, false)
32 pub(super) fn parse_item_(
34 attrs: Vec<Attribute>,
36 attributes_allowed: bool,
37 ) -> PResult<'a, Option<P<Item>>> {
38 let mut unclosed_delims = vec![];
39 let (ret, tokens) = self.collect_tokens(|this| {
40 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
41 unclosed_delims.append(&mut this.unclosed_delims);
44 self.unclosed_delims.append(&mut unclosed_delims);
46 // Once we've parsed an item and recorded the tokens we got while
47 // parsing we may want to store `tokens` into the item we're about to
48 // return. Note, though, that we specifically didn't capture tokens
49 // related to outer attributes. The `tokens` field here may later be
50 // used with procedural macros to convert this item back into a token
51 // stream, but during expansion we may be removing attributes as we go
54 // If we've got inner attributes then the `tokens` we've got above holds
55 // these inner attributes. If an inner attribute is expanded we won't
56 // actually remove it from the token stream, so we'll just keep yielding
57 // it (bad!). To work around this case for now we just avoid recording
58 // `tokens` if we detect any inner attributes. This should help keep
59 // expansion correct, but we should fix this bug one day!
62 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
63 i.tokens = Some(tokens);
70 /// Parses one of the items allowed by the flags.
71 fn parse_item_implementation(
73 attrs: Vec<Attribute>,
75 attributes_allowed: bool,
76 ) -> PResult<'a, Option<P<Item>>> {
77 maybe_whole!(self, NtItem, |item| {
78 let mut item = item.into_inner();
79 let mut attrs = attrs;
80 mem::swap(&mut item.attrs, &mut attrs);
81 item.attrs.extend(attrs);
85 let lo = self.token.span;
87 let vis = self.parse_visibility(FollowedByType::No)?;
89 if self.eat_keyword(kw::Use) {
91 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
94 let span = lo.to(self.prev_span);
95 let item = self.mk_item(span, Ident::invalid(), item_, vis, attrs);
96 return Ok(Some(item));
99 if self.eat_keyword(kw::Extern) {
100 let extern_sp = self.prev_span;
101 if self.eat_keyword(kw::Crate) {
102 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
105 let abi = self.parse_abi();
107 if self.eat_keyword(kw::Fn) {
108 // EXTERN FUNCTION ITEM
109 let fn_span = self.prev_span;
110 let header = FnHeader {
111 unsafety: Unsafety::Normal,
112 asyncness: respan(fn_span, IsAsync::NotAsync),
113 constness: respan(fn_span, Constness::NotConst),
114 ext: Extern::from_abi(abi),
116 return self.parse_item_fn(lo, vis, attrs, header);
117 } else if self.check(&token::OpenDelim(token::Brace)) {
118 return Ok(Some(self.parse_item_foreign_mod(lo, abi, vis, attrs, extern_sp)?));
124 if self.is_static_global() {
127 let m = self.parse_mutability();
128 let info = self.parse_item_const(Some(m))?;
129 return self.mk_item_with_info(attrs, lo, vis, info);
132 if self.eat_keyword(kw::Const) {
133 let const_span = self.prev_span;
134 if [kw::Fn, kw::Unsafe, kw::Extern].iter().any(|k| self.check_keyword(*k)) {
135 // CONST FUNCTION ITEM
136 let unsafety = self.parse_unsafety();
138 if self.check_keyword(kw::Extern) {
139 self.sess.gated_spans.gate(sym::const_extern_fn, lo.to(self.token.span));
141 let ext = self.parse_extern()?;
142 self.expect_keyword(kw::Fn)?;
144 let header = FnHeader {
146 asyncness: respan(const_span, IsAsync::NotAsync),
147 constness: respan(const_span, Constness::Const),
150 return self.parse_item_fn(lo, vis, attrs, header);
154 if self.eat_keyword(kw::Mut) {
155 let prev_span = self.prev_span;
156 self.struct_span_err(prev_span, "const globals cannot be mutable")
157 .span_label(prev_span, "cannot be mutable")
160 "you might want to declare a static instead",
162 Applicability::MaybeIncorrect,
167 let info = self.parse_item_const(None)?;
168 return self.mk_item_with_info(attrs, lo, vis, info);
171 // Parses `async unsafe? fn`.
172 if self.check_keyword(kw::Async) {
173 let async_span = self.token.span;
174 if self.is_keyword_ahead(1, &[kw::Fn]) || self.is_keyword_ahead(2, &[kw::Fn]) {
175 // ASYNC FUNCTION ITEM
176 self.bump(); // `async`
177 let unsafety = self.parse_unsafety(); // `unsafe`?
178 self.expect_keyword(kw::Fn)?; // `fn`
179 let fn_span = self.prev_span;
180 let asyncness = respan(
183 closure_id: DUMMY_NODE_ID,
184 return_impl_trait_id: DUMMY_NODE_ID,
187 self.ban_async_in_2015(async_span);
188 let header = FnHeader {
191 constness: respan(fn_span, Constness::NotConst),
194 return self.parse_item_fn(lo, vis, attrs, header);
198 if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) {
200 self.bump(); // `unsafe`
201 let info = self.parse_item_trait(lo, Unsafety::Unsafe)?;
202 return self.mk_item_with_info(attrs, lo, vis, info);
205 if self.check_keyword(kw::Impl)
206 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
207 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
210 let defaultness = self.parse_defaultness();
211 let unsafety = self.parse_unsafety();
212 self.expect_keyword(kw::Impl)?;
213 let info = self.parse_item_impl(unsafety, defaultness)?;
214 return self.mk_item_with_info(attrs, lo, vis, info);
217 if self.check_keyword(kw::Fn) {
220 let fn_span = self.prev_span;
221 let header = FnHeader {
222 unsafety: Unsafety::Normal,
223 asyncness: respan(fn_span, IsAsync::NotAsync),
224 constness: respan(fn_span, Constness::NotConst),
227 return self.parse_item_fn(lo, vis, attrs, header);
230 if self.check_keyword(kw::Unsafe)
231 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace))
233 // UNSAFE FUNCTION ITEM
234 self.bump(); // `unsafe`
235 // `{` is also expected after `unsafe`; in case of error, include it in the diagnostic.
236 self.check(&token::OpenDelim(token::Brace));
237 let ext = self.parse_extern()?;
238 self.expect_keyword(kw::Fn)?;
239 let fn_span = self.prev_span;
240 let header = FnHeader {
241 unsafety: Unsafety::Unsafe,
242 asyncness: respan(fn_span, IsAsync::NotAsync),
243 constness: respan(fn_span, Constness::NotConst),
246 return self.parse_item_fn(lo, vis, attrs, header);
249 if self.eat_keyword(kw::Mod) {
251 let info = self.parse_item_mod(&attrs[..])?;
252 return self.mk_item_with_info(attrs, lo, vis, info);
255 if self.eat_keyword(kw::Type) {
257 let (ident, ty, generics) = self.parse_type_alias()?;
258 let kind = ItemKind::TyAlias(ty, generics);
259 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
262 if self.eat_keyword(kw::Enum) {
264 let info = self.parse_item_enum()?;
265 return self.mk_item_with_info(attrs, lo, vis, info);
268 if self.check_keyword(kw::Trait)
269 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
272 let info = self.parse_item_trait(lo, Unsafety::Normal)?;
273 return self.mk_item_with_info(attrs, lo, vis, info);
276 if self.eat_keyword(kw::Struct) {
278 let info = self.parse_item_struct()?;
279 return self.mk_item_with_info(attrs, lo, vis, info);
282 if self.is_union_item() {
285 let info = self.parse_item_union()?;
286 return self.mk_item_with_info(attrs, lo, vis, info);
289 if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? {
290 return Ok(Some(macro_def));
293 // Verify whether we have encountered a struct or method definition where the user forgot to
294 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
295 if vis.node.is_pub() && self.check_ident() && self.look_ahead(1, |t| *t != token::Not) {
296 // Space between `pub` keyword and the identifier
299 // ^^^ `sp` points here
300 let sp = self.prev_span.between(self.token.span);
301 let full_sp = self.prev_span.to(self.token.span);
302 let ident_sp = self.token.span;
303 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
304 // possible public struct definition where `struct` was forgotten
305 let ident = self.parse_ident().unwrap();
306 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
307 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
308 err.span_suggestion_short(
312 Applicability::MaybeIncorrect, // speculative
315 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
316 let ident = self.parse_ident().unwrap();
318 let kw_name = self.recover_first_param();
319 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
320 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
321 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
323 ("fn", kw_name, false)
324 } else if self.check(&token::OpenDelim(token::Brace)) {
326 ("fn", kw_name, false)
327 } else if self.check(&token::Colon) {
331 ("fn` or `struct", "function or struct", true)
334 let msg = format!("missing `{}` for {} definition", kw, kw_name);
335 let mut err = self.struct_span_err(sp, &msg);
337 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
339 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
340 err.span_suggestion_short(
344 Applicability::MachineApplicable,
347 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
350 "if you meant to call a macro, try",
351 format!("{}!", snippet),
352 // this is the `ambiguous` conditional branch
353 Applicability::MaybeIncorrect,
357 "if you meant to call a macro, remove the `pub` \
358 and add a trailing `!` after the identifier",
363 } else if self.look_ahead(1, |t| *t == token::Lt) {
364 let ident = self.parse_ident().unwrap();
365 self.eat_to_tokens(&[&token::Gt]);
367 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
368 ("fn", self.recover_first_param(), false)
369 } else if self.check(&token::OpenDelim(token::Brace)) {
370 ("struct", "struct", false)
372 ("fn` or `struct", "function or struct", true)
374 let msg = format!("missing `{}` for {} definition", kw, kw_name);
375 let mut err = self.struct_span_err(sp, &msg);
377 err.span_suggestion_short(
379 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
381 Applicability::MachineApplicable,
387 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis)
390 pub(super) fn mk_item_with_info(
392 attrs: Vec<Attribute>,
396 ) -> PResult<'a, Option<P<Item>>> {
397 let (ident, item, extra_attrs) = info;
398 let span = lo.to(self.prev_span);
399 let attrs = Self::maybe_append(attrs, extra_attrs);
400 Ok(Some(self.mk_item(span, ident, item, vis, attrs)))
403 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
404 if let Some(ref mut rhs) = rhs {
410 /// This is the fall-through for parsing items.
411 fn parse_macro_use_or_failure(
413 attrs: Vec<Attribute>,
414 macros_allowed: bool,
415 attributes_allowed: bool,
417 visibility: Visibility,
418 ) -> PResult<'a, Option<P<Item>>> {
420 && self.token.is_path_start()
421 && !(self.is_async_fn() && self.token.span.rust_2015())
423 // MACRO INVOCATION ITEM
425 let prev_span = self.prev_span;
426 self.complain_if_pub_macro(&visibility.node, prev_span);
429 let path = self.parse_path(PathStyle::Mod)?;
430 self.expect(&token::Not)?;
431 let args = self.parse_mac_args()?;
432 if args.need_semicolon() && !self.eat(&token::Semi) {
433 self.report_invalid_macro_expansion_item();
436 let hi = self.prev_span;
437 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
439 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
440 return Ok(Some(item));
443 // FAILURE TO PARSE ITEM
444 match visibility.node {
445 VisibilityKind::Inherited => {}
446 _ => return Err(self.struct_span_err(self.prev_span, "unmatched visibility `pub`")),
449 if !attributes_allowed && !attrs.is_empty() {
450 self.expected_item_err(&attrs)?;
455 /// Emits an expected-item-after-attributes error.
456 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
457 let message = match attrs.last() {
458 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
459 "expected item after doc comment"
461 _ => "expected item after attributes",
464 let mut err = self.struct_span_err(self.prev_span, message);
465 if attrs.last().unwrap().is_doc_comment() {
466 err.span_label(self.prev_span, "this doc comment doesn't document anything");
471 pub(super) fn is_async_fn(&self) -> bool {
472 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
475 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
476 fn parse_assoc_macro_invoc(
479 vis: Option<&Visibility>,
481 ) -> PResult<'a, Option<Mac>> {
482 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
483 let prev_span = self.prev_span;
484 let path = self.parse_path(PathStyle::Mod)?;
486 if path.segments.len() == 1 {
487 if !self.eat(&token::Not) {
488 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
491 self.expect(&token::Not)?;
494 if let Some(vis) = vis {
495 self.complain_if_pub_macro(&vis.node, prev_span);
500 // eat a matched-delimiter token tree:
501 let args = self.parse_mac_args()?;
502 if args.need_semicolon() {
506 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
512 fn missing_assoc_item_kind_err(
516 ) -> DiagnosticBuilder<'a> {
517 let expected_kinds = if item_type == "extern" {
518 "missing `fn`, `type`, or `static`"
520 "missing `fn`, `type`, or `const`"
523 // Given this code `path(`, it seems like this is not
524 // setting the visibility of a macro invocation, but rather
525 // a mistyped method declaration.
526 // Create a diagnostic pointing out that `fn` is missing.
528 // x | pub path(&self) {
529 // | ^ missing `fn`, `type`, or `const`
531 // ^^ `sp` below will point to this
532 let sp = prev_span.between(self.prev_span);
534 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
535 err.span_label(sp, expected_kinds);
539 /// Parses an implementation item, `impl` keyword is already parsed.
541 /// impl<'a, T> TYPE { /* impl items */ }
542 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
543 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
544 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
546 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
547 /// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
548 /// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
552 defaultness: Defaultness,
553 ) -> PResult<'a, ItemInfo> {
554 // First, parse generic parameters if necessary.
555 let mut generics = if self.choose_generics_over_qpath() {
556 self.parse_generics()?
558 let mut generics = Generics::default();
560 // /\ this is where `generics.span` should point when there are no type params.
561 generics.span = self.prev_span.shrink_to_hi();
565 let constness = if self.eat_keyword(kw::Const) {
566 let span = self.prev_span;
567 self.sess.gated_spans.gate(sym::const_trait_impl, span);
573 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
574 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
576 ast::ImplPolarity::Negative
578 ast::ImplPolarity::Positive
581 // Parse both types and traits as a type, then reinterpret if necessary.
582 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
583 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
585 let span = self.prev_span.between(self.token.span);
586 self.struct_span_err(span, "missing trait in a trait impl").emit();
587 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
592 // If `for` is missing we try to recover.
593 let has_for = self.eat_keyword(kw::For);
594 let missing_for_span = self.prev_span.between(self.token.span);
596 let ty_second = if self.token == token::DotDot {
597 // We need to report this error after `cfg` expansion for compatibility reasons
598 self.bump(); // `..`, do not add it to expected tokens
599 Some(self.mk_ty(self.prev_span, TyKind::Err))
600 } else if has_for || self.token.can_begin_type() {
601 Some(self.parse_ty()?)
606 generics.where_clause = self.parse_where_clause()?;
608 let (impl_items, attrs) = self.parse_impl_body()?;
610 let item_kind = match ty_second {
612 // impl Trait for Type
614 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
615 .span_suggestion_short(
619 Applicability::MachineApplicable,
624 let ty_first = ty_first.into_inner();
625 let path = match ty_first.kind {
626 // This notably includes paths passed through `ty` macro fragments (#46438).
627 TyKind::Path(None, path) => path,
629 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
630 err_path(ty_first.span)
633 let trait_ref = TraitRef { path, ref_id: ty_first.id };
641 of_trait: Some(trait_ref),
661 Ok((Ident::invalid(), item_kind, Some(attrs)))
664 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<P<AssocItem>>, Vec<Attribute>)> {
665 self.expect(&token::OpenDelim(token::Brace))?;
666 let attrs = self.parse_inner_attributes()?;
668 let mut impl_items = Vec::new();
669 while !self.eat(&token::CloseDelim(token::Brace)) {
670 let mut at_end = false;
671 match self.parse_impl_item(&mut at_end) {
672 Ok(impl_item) => impl_items.push(impl_item),
676 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
682 Ok((impl_items, attrs))
685 /// Parses defaultness (i.e., `default` or nothing).
686 fn parse_defaultness(&mut self) -> Defaultness {
687 // `pub` is included for better error messages
688 if self.check_keyword(kw::Default)
689 && self.is_keyword_ahead(
703 self.bump(); // `default`
710 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
711 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
712 // Parse optional `auto` prefix.
713 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
715 self.expect_keyword(kw::Trait)?;
716 let ident = self.parse_ident()?;
717 let mut tps = self.parse_generics()?;
719 // Parse optional colon and supertrait bounds.
720 let had_colon = self.eat(&token::Colon);
721 let span_at_colon = self.prev_span;
723 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
725 let span_before_eq = self.prev_span;
726 if self.eat(&token::Eq) {
727 // It's a trait alias.
729 let span = span_at_colon.to(span_before_eq);
730 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
733 let bounds = self.parse_generic_bounds(None)?;
734 tps.where_clause = self.parse_where_clause()?;
737 let whole_span = lo.to(self.prev_span);
738 if is_auto == IsAuto::Yes {
739 let msg = "trait aliases cannot be `auto`";
740 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
742 if unsafety != Unsafety::Normal {
743 let msg = "trait aliases cannot be `unsafe`";
744 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
747 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
749 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
751 // It's a normal trait.
752 tps.where_clause = self.parse_where_clause()?;
753 self.expect(&token::OpenDelim(token::Brace))?;
754 let mut trait_items = vec![];
755 while !self.eat(&token::CloseDelim(token::Brace)) {
756 if let token::DocComment(_) = self.token.kind {
757 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
762 "found a documentation comment that doesn't document anything",
765 "doc comments must come before what they document, maybe a \
766 comment was intended with `//`?",
773 let mut at_end = false;
774 match self.parse_trait_item(&mut at_end) {
775 Ok(item) => trait_items.push(item),
779 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
785 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
789 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
790 maybe_whole!(self, NtImplItem, |x| x);
791 self.parse_assoc_item(at_end, |_| true)
794 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
795 maybe_whole!(self, NtTraitItem, |x| x);
796 // This is somewhat dubious; We don't want to allow
797 // param names to be left off if there is a definition...
799 // We don't allow param names to be left off in edition 2018.
800 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
803 /// Parses associated items.
807 is_name_required: fn(&token::Token) -> bool,
808 ) -> PResult<'a, P<AssocItem>> {
809 let attrs = self.parse_outer_attributes()?;
810 let mut unclosed_delims = vec![];
811 let (mut item, tokens) = self.collect_tokens(|this| {
812 let item = this.parse_assoc_item_(at_end, attrs, is_name_required);
813 unclosed_delims.append(&mut this.unclosed_delims);
816 self.unclosed_delims.append(&mut unclosed_delims);
817 // See `parse_item` for why this clause is here.
818 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
819 item.tokens = Some(tokens);
824 fn parse_assoc_item_(
827 mut attrs: Vec<Attribute>,
828 is_name_required: fn(&token::Token) -> bool,
829 ) -> PResult<'a, AssocItem> {
830 let lo = self.token.span;
831 let vis = self.parse_visibility(FollowedByType::No)?;
832 let defaultness = self.parse_defaultness();
833 let (name, kind, generics) = if self.eat_keyword(kw::Type) {
834 self.parse_assoc_ty()?
835 } else if self.is_const_item() {
836 self.parse_assoc_const()?
837 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
838 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
840 self.parse_assoc_fn(at_end, &mut attrs, is_name_required)?
845 span: lo.to(self.prev_span),
856 /// Returns `true` if we are looking at `const ID`
857 /// (returns `false` for things like `const fn`, etc.).
858 fn is_const_item(&self) -> bool {
859 self.token.is_keyword(kw::Const) && !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
862 /// This parses the grammar:
864 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
865 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
866 self.expect_keyword(kw::Const)?;
867 let ident = self.parse_ident()?;
868 self.expect(&token::Colon)?;
869 let ty = self.parse_ty()?;
870 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
872 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
875 /// Parses the following grammar:
877 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
878 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
879 let ident = self.parse_ident()?;
880 let mut generics = self.parse_generics()?;
882 // Parse optional colon and param bounds.
884 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
885 generics.where_clause = self.parse_where_clause()?;
887 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
890 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
893 /// Parses a `UseTree`.
896 /// USE_TREE = [`::`] `*` |
897 /// [`::`] `{` USE_TREE_LIST `}` |
899 /// PATH `::` `{` USE_TREE_LIST `}` |
900 /// PATH [`as` IDENT]
902 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
903 let lo = self.token.span;
905 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
906 let kind = if self.check(&token::OpenDelim(token::Brace))
907 || self.check(&token::BinOp(token::Star))
908 || self.is_import_coupler()
910 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
911 let mod_sep_ctxt = self.token.span.ctxt();
912 if self.eat(&token::ModSep) {
915 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
918 self.parse_use_tree_glob_or_nested()?
920 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
921 prefix = self.parse_path(PathStyle::Mod)?;
923 if self.eat(&token::ModSep) {
924 self.parse_use_tree_glob_or_nested()?
926 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
930 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
933 /// Parses `*` or `{...}`.
934 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
935 Ok(if self.eat(&token::BinOp(token::Star)) {
938 UseTreeKind::Nested(self.parse_use_tree_list()?)
942 /// Parses a `UseTreeKind::Nested(list)`.
945 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
947 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
948 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
952 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
953 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
956 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
957 match self.token.kind {
958 token::Ident(name, false) if name == kw::Underscore => {
959 let span = self.token.span;
961 Ok(Ident::new(name, span))
963 _ => self.parse_ident(),
967 /// Parses `extern crate` links.
972 /// extern crate foo;
973 /// extern crate bar as foo;
975 fn parse_item_extern_crate(
978 visibility: Visibility,
979 attrs: Vec<Attribute>,
980 ) -> PResult<'a, P<Item>> {
981 // Accept `extern crate name-like-this` for better diagnostics
982 let orig_name = self.parse_crate_name_with_dashes()?;
983 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
984 (rename, Some(orig_name.name))
990 let span = lo.to(self.prev_span);
991 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
994 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
995 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
996 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
998 let mut ident = if self.token.is_keyword(kw::SelfLower) {
999 self.parse_path_segment_ident()
1003 let mut idents = vec![];
1004 let mut replacement = vec![];
1005 let mut fixed_crate_name = false;
1006 // Accept `extern crate name-like-this` for better diagnostics.
1007 let dash = token::BinOp(token::BinOpToken::Minus);
1008 if self.token == dash {
1009 // Do not include `-` as part of the expected tokens list.
1010 while self.eat(&dash) {
1011 fixed_crate_name = true;
1012 replacement.push((self.prev_span, "_".to_string()));
1013 idents.push(self.parse_ident()?);
1016 if fixed_crate_name {
1017 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1018 let mut fixed_name = format!("{}", ident.name);
1019 for part in idents {
1020 fixed_name.push_str(&format!("_{}", part.name));
1022 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1024 self.struct_span_err(fixed_name_sp, error_msg)
1025 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1026 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1032 /// Parses `extern` for foreign ABIs modules.
1034 /// `extern` is expected to have been
1035 /// consumed before calling this method.
1039 /// ```ignore (only-for-syntax-highlight)
1043 fn parse_item_foreign_mod(
1046 abi: Option<StrLit>,
1047 visibility: Visibility,
1048 mut attrs: Vec<Attribute>,
1050 ) -> PResult<'a, P<Item>> {
1051 self.expect(&token::OpenDelim(token::Brace))?;
1053 attrs.extend(self.parse_inner_attributes()?);
1055 let mut foreign_items = vec![];
1056 while !self.eat(&token::CloseDelim(token::Brace)) {
1057 foreign_items.push(self.parse_foreign_item(extern_sp)?);
1060 let prev_span = self.prev_span;
1061 let m = ast::ForeignMod { abi, items: foreign_items };
1062 let invalid = Ident::invalid();
1063 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
1066 /// Parses a foreign item.
1067 pub fn parse_foreign_item(&mut self, extern_sp: Span) -> PResult<'a, P<ForeignItem>> {
1068 maybe_whole!(self, NtForeignItem, |ni| ni);
1070 let attrs = self.parse_outer_attributes()?;
1071 let lo = self.token.span;
1072 let visibility = self.parse_visibility(FollowedByType::No)?;
1074 // FOREIGN STATIC ITEM
1075 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
1076 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
1077 if self.token.is_keyword(kw::Const) {
1079 self.struct_span_err(self.token.span, "extern items cannot be `const`");
1081 // The user wrote 'const fn'
1082 if self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) {
1086 // Consume `unsafe` if present, since `extern` blocks
1087 // don't allow it. This will leave behind a plain 'fn'
1088 self.eat_keyword(kw::Unsafe);
1089 // Treat 'const fn` as a plain `fn` for error recovery purposes.
1090 // We've already emitted an error, so compilation is guaranteed
1092 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
1094 err.span_suggestion(
1096 "try using a static value",
1097 "static".to_owned(),
1098 Applicability::MachineApplicable,
1102 self.bump(); // `static` or `const`
1103 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
1105 // FOREIGN FUNCTION ITEM
1106 if self.check_keyword(kw::Fn) {
1107 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
1109 // FOREIGN TYPE ITEM
1110 if self.check_keyword(kw::Type) {
1111 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
1114 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
1115 Some(mac) => Ok(P(ForeignItem {
1116 ident: Ident::invalid(),
1117 span: lo.to(self.prev_span),
1121 kind: ForeignItemKind::Macro(mac),
1125 if !attrs.is_empty() {
1126 self.expected_item_err(&attrs)?;
1134 /// Parses a static item from a foreign module.
1135 /// Assumes that the `static` keyword is already parsed.
1136 fn parse_item_foreign_static(
1138 vis: ast::Visibility,
1140 attrs: Vec<Attribute>,
1141 ) -> PResult<'a, P<ForeignItem>> {
1142 let mutbl = self.parse_mutability();
1143 let ident = self.parse_ident()?;
1144 self.expect(&token::Colon)?;
1145 let ty = self.parse_ty()?;
1146 let hi = self.token.span;
1147 self.expect_semi()?;
1151 kind: ForeignItemKind::Static(ty, mutbl),
1159 /// Parses a type from a foreign module.
1160 fn parse_item_foreign_type(
1162 vis: ast::Visibility,
1164 attrs: Vec<Attribute>,
1165 ) -> PResult<'a, P<ForeignItem>> {
1166 self.expect_keyword(kw::Type)?;
1168 let ident = self.parse_ident()?;
1169 let hi = self.token.span;
1170 self.expect_semi()?;
1171 Ok(P(ast::ForeignItem {
1174 kind: ForeignItemKind::Ty,
1182 fn is_static_global(&mut self) -> bool {
1183 if self.check_keyword(kw::Static) {
1184 // Check if this could be a closure.
1185 !self.look_ahead(1, |token| {
1186 if token.is_keyword(kw::Move) {
1190 token::BinOp(token::Or) | token::OrOr => true,
1199 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1200 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1202 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1203 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1204 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1206 // Parse the type of a `const` or `static mut?` item.
1207 // That is, the `":" $ty` fragment.
1208 let ty = if self.token == token::Eq {
1209 self.recover_missing_const_type(id, m)
1211 // Not `=` so expect `":"" $ty` as usual.
1212 self.expect(&token::Colon)?;
1216 self.expect(&token::Eq)?;
1217 let e = self.parse_expr()?;
1218 self.expect_semi()?;
1219 let item = match m {
1220 Some(m) => ItemKind::Static(ty, m, e),
1221 None => ItemKind::Const(ty, e),
1223 Ok((id, item, None))
1226 /// We were supposed to parse `:` but instead, we're already at `=`.
1227 /// This means that the type is missing.
1228 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1229 // Construct the error and stash it away with the hope
1230 // that typeck will later enrich the error with a type.
1231 let kind = match m {
1232 Some(Mutability::Mut) => "static mut",
1233 Some(Mutability::Not) => "static",
1236 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1237 err.span_suggestion(
1239 "provide a type for the item",
1240 format!("{}: <type>", id),
1241 Applicability::HasPlaceholders,
1243 err.stash(id.span, StashKey::ItemNoType);
1245 // The user intended that the type be inferred,
1246 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1247 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1250 /// Parses the grammar:
1251 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1252 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1253 let ident = self.parse_ident()?;
1254 let mut tps = self.parse_generics()?;
1255 tps.where_clause = self.parse_where_clause()?;
1256 self.expect(&token::Eq)?;
1257 let ty = self.parse_ty()?;
1258 self.expect_semi()?;
1259 Ok((ident, ty, tps))
1262 /// Parses an enum declaration.
1263 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1264 let id = self.parse_ident()?;
1265 let mut generics = self.parse_generics()?;
1266 generics.where_clause = self.parse_where_clause()?;
1269 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1270 self.recover_stmt();
1274 let enum_definition =
1275 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1276 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1279 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1280 let variant_attrs = self.parse_outer_attributes()?;
1281 let vlo = self.token.span;
1283 let vis = self.parse_visibility(FollowedByType::No)?;
1284 if !self.recover_nested_adt_item(kw::Enum)? {
1287 let ident = self.parse_ident()?;
1289 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1290 // Parse a struct variant.
1291 let (fields, recovered) = self.parse_record_struct_body()?;
1292 VariantData::Struct(fields, recovered)
1293 } else if self.check(&token::OpenDelim(token::Paren)) {
1294 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1296 VariantData::Unit(DUMMY_NODE_ID)
1300 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1302 let vr = ast::Variant {
1306 attrs: variant_attrs,
1309 span: vlo.to(self.prev_span),
1310 is_placeholder: false,
1316 /// Parses `struct Foo { ... }`.
1317 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1318 let class_name = self.parse_ident()?;
1320 let mut generics = self.parse_generics()?;
1322 // There is a special case worth noting here, as reported in issue #17904.
1323 // If we are parsing a tuple struct it is the case that the where clause
1324 // should follow the field list. Like so:
1326 // struct Foo<T>(T) where T: Copy;
1328 // If we are parsing a normal record-style struct it is the case
1329 // that the where clause comes before the body, and after the generics.
1330 // So if we look ahead and see a brace or a where-clause we begin
1331 // parsing a record style struct.
1333 // Otherwise if we look ahead and see a paren we parse a tuple-style
1336 let vdata = if self.token.is_keyword(kw::Where) {
1337 generics.where_clause = self.parse_where_clause()?;
1338 if self.eat(&token::Semi) {
1339 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1340 VariantData::Unit(DUMMY_NODE_ID)
1342 // If we see: `struct Foo<T> where T: Copy { ... }`
1343 let (fields, recovered) = self.parse_record_struct_body()?;
1344 VariantData::Struct(fields, recovered)
1346 // No `where` so: `struct Foo<T>;`
1347 } else if self.eat(&token::Semi) {
1348 VariantData::Unit(DUMMY_NODE_ID)
1349 // Record-style struct definition
1350 } else if self.token == token::OpenDelim(token::Brace) {
1351 let (fields, recovered) = self.parse_record_struct_body()?;
1352 VariantData::Struct(fields, recovered)
1353 // Tuple-style struct definition with optional where-clause.
1354 } else if self.token == token::OpenDelim(token::Paren) {
1355 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1356 generics.where_clause = self.parse_where_clause()?;
1357 self.expect_semi()?;
1360 let token_str = super::token_descr(&self.token);
1362 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1365 let mut err = self.struct_span_err(self.token.span, msg);
1366 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1370 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1373 /// Parses `union Foo { ... }`.
1374 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1375 let class_name = self.parse_ident()?;
1377 let mut generics = self.parse_generics()?;
1379 let vdata = if self.token.is_keyword(kw::Where) {
1380 generics.where_clause = self.parse_where_clause()?;
1381 let (fields, recovered) = self.parse_record_struct_body()?;
1382 VariantData::Struct(fields, recovered)
1383 } else if self.token == token::OpenDelim(token::Brace) {
1384 let (fields, recovered) = self.parse_record_struct_body()?;
1385 VariantData::Struct(fields, recovered)
1387 let token_str = super::token_descr(&self.token);
1388 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1389 let mut err = self.struct_span_err(self.token.span, msg);
1390 err.span_label(self.token.span, "expected `where` or `{` after union name");
1394 Ok((class_name, ItemKind::Union(vdata, generics), None))
1397 pub(super) fn is_union_item(&self) -> bool {
1398 self.token.is_keyword(kw::Union)
1399 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1402 fn parse_record_struct_body(
1404 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1405 let mut fields = Vec::new();
1406 let mut recovered = false;
1407 if self.eat(&token::OpenDelim(token::Brace)) {
1408 while self.token != token::CloseDelim(token::Brace) {
1409 let field = self.parse_struct_decl_field().map_err(|e| {
1410 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1415 Ok(field) => fields.push(field),
1422 self.eat(&token::CloseDelim(token::Brace));
1424 let token_str = super::token_descr(&self.token);
1425 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1426 let mut err = self.struct_span_err(self.token.span, msg);
1427 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1431 Ok((fields, recovered))
1434 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1435 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1436 // Unit like structs are handled in parse_item_struct function
1437 self.parse_paren_comma_seq(|p| {
1438 let attrs = p.parse_outer_attributes()?;
1439 let lo = p.token.span;
1440 let vis = p.parse_visibility(FollowedByType::Yes)?;
1441 let ty = p.parse_ty()?;
1443 span: lo.to(ty.span),
1449 is_placeholder: false,
1455 /// Parses an element of a struct declaration.
1456 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1457 let attrs = self.parse_outer_attributes()?;
1458 let lo = self.token.span;
1459 let vis = self.parse_visibility(FollowedByType::No)?;
1460 self.parse_single_struct_field(lo, vis, attrs)
1463 /// Parses a structure field declaration.
1464 fn parse_single_struct_field(
1468 attrs: Vec<Attribute>,
1469 ) -> PResult<'a, StructField> {
1470 let mut seen_comma: bool = false;
1471 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1472 if self.token == token::Comma {
1475 match self.token.kind {
1479 token::CloseDelim(token::Brace) => {}
1480 token::DocComment(_) => {
1481 let previous_span = self.prev_span;
1482 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1483 self.bump(); // consume the doc comment
1484 let comma_after_doc_seen = self.eat(&token::Comma);
1485 // `seen_comma` is always false, because we are inside doc block
1486 // condition is here to make code more readable
1487 if seen_comma == false && comma_after_doc_seen == true {
1490 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1493 if seen_comma == false {
1494 let sp = self.sess.source_map().next_point(previous_span);
1495 err.span_suggestion(
1497 "missing comma here",
1499 Applicability::MachineApplicable,
1506 let sp = self.prev_span.shrink_to_hi();
1507 let mut err = self.struct_span_err(
1509 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1511 if self.token.is_ident() {
1512 // This is likely another field; emit the diagnostic and keep going
1513 err.span_suggestion(
1515 "try adding a comma",
1517 Applicability::MachineApplicable,
1528 /// Parses a structure field.
1529 fn parse_name_and_ty(
1533 attrs: Vec<Attribute>,
1534 ) -> PResult<'a, StructField> {
1535 let name = self.parse_ident()?;
1536 self.expect(&token::Colon)?;
1537 let ty = self.parse_ty()?;
1539 span: lo.to(self.prev_span),
1545 is_placeholder: false,
1549 pub(super) fn eat_macro_def(
1551 attrs: &[Attribute],
1554 ) -> PResult<'a, Option<P<Item>>> {
1555 let (ident, def) = if self.eat_keyword(kw::Macro) {
1556 let ident = self.parse_ident()?;
1557 let body = if self.check(&token::OpenDelim(token::Brace)) {
1558 self.parse_mac_args()?
1559 } else if self.check(&token::OpenDelim(token::Paren)) {
1560 let params = self.parse_token_tree();
1561 let pspan = params.span();
1562 let body = if self.check(&token::OpenDelim(token::Brace)) {
1563 self.parse_token_tree()
1565 return self.unexpected();
1567 let bspan = body.span();
1568 let tokens = TokenStream::new(vec![
1570 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1573 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1574 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1576 return self.unexpected();
1579 (ident, ast::MacroDef { body, legacy: false })
1580 } else if self.check_keyword(sym::macro_rules)
1581 && self.look_ahead(1, |t| *t == token::Not)
1582 && self.look_ahead(2, |t| t.is_ident())
1584 let prev_span = self.prev_span;
1585 self.complain_if_pub_macro(&vis.node, prev_span);
1589 let ident = self.parse_ident()?;
1590 let body = self.parse_mac_args()?;
1591 if body.need_semicolon() && !self.eat(&token::Semi) {
1592 self.report_invalid_macro_expansion_item();
1595 (ident, ast::MacroDef { body, legacy: true })
1600 let span = lo.to(self.prev_span);
1603 self.sess.gated_spans.gate(sym::decl_macro, span);
1606 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1609 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1611 VisibilityKind::Inherited => {}
1613 let mut err = if self.token.is_keyword(sym::macro_rules) {
1615 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1616 err.span_suggestion(
1618 "try exporting the macro",
1619 "#[macro_export]".to_owned(),
1620 Applicability::MaybeIncorrect, // speculative
1625 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1626 err.help("try adjusting the macro to put `pub` inside the invocation");
1634 fn report_invalid_macro_expansion_item(&self) {
1635 let has_close_delim = self
1638 .span_to_snippet(self.prev_span)
1639 .map(|s| s.ends_with(")") || s.ends_with("]"))
1642 let mut err = self.struct_span_err(
1644 "macros that expand to items must be delimited with braces or followed by a semicolon",
1647 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1648 if has_close_delim {
1649 err.multipart_suggestion(
1650 "change the delimiters to curly braces",
1652 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1653 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1655 Applicability::MaybeIncorrect,
1658 err.span_suggestion(
1660 "change the delimiters to curly braces",
1661 " { /* items */ }".to_string(),
1662 Applicability::HasPlaceholders,
1666 err.span_suggestion(
1667 self.prev_span.shrink_to_hi(),
1670 Applicability::MaybeIncorrect,
1675 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1676 /// it is, we try to parse the item and report error about nested types.
1677 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1678 if (self.token.is_keyword(kw::Enum)
1679 || self.token.is_keyword(kw::Struct)
1680 || self.token.is_keyword(kw::Union))
1681 && self.look_ahead(1, |t| t.is_ident())
1683 let kw_token = self.token.clone();
1684 let kw_str = pprust::token_to_string(&kw_token);
1685 let item = self.parse_item()?;
1687 self.struct_span_err(
1689 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1693 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1695 Applicability::MaybeIncorrect,
1698 // We successfully parsed the item but we must inform the caller about nested problem.
1710 attrs: Vec<Attribute>,
1712 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1716 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1717 pub(super) struct ParamCfg {
1718 /// Is `self` is *semantically* allowed as the first parameter?
1719 /// This is only used for diagnostics.
1720 pub in_assoc_item: bool,
1721 /// `is_name_required` decides if, per-parameter,
1722 /// the parameter must have a pattern or just a type.
1723 pub is_name_required: fn(&token::Token) -> bool,
1726 /// Parsing of functions and methods.
1727 impl<'a> Parser<'a> {
1728 /// Parses an item-position function declaration.
1733 attrs: Vec<Attribute>,
1735 ) -> PResult<'a, Option<P<Item>>> {
1736 let cfg = ParamCfg { in_assoc_item: false, is_name_required: |_| true };
1737 let (ident, decl, generics) = self.parse_fn_sig(&cfg)?;
1738 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1739 let kind = ItemKind::Fn(FnSig { decl, header }, generics, body);
1740 self.mk_item_with_info(attrs, lo, vis, (ident, kind, Some(inner_attrs)))
1743 /// Parses a function declaration from a foreign module.
1744 fn parse_item_foreign_fn(
1746 vis: ast::Visibility,
1748 attrs: Vec<Attribute>,
1750 ) -> PResult<'a, P<ForeignItem>> {
1751 let cfg = ParamCfg { in_assoc_item: false, is_name_required: |_| true };
1752 self.expect_keyword(kw::Fn)?;
1753 let (ident, decl, generics) = self.parse_fn_sig(&cfg)?;
1754 let span = lo.to(self.token.span);
1755 self.parse_semi_or_incorrect_foreign_fn_body(&ident, extern_sp)?;
1756 let kind = ForeignItemKind::Fn(decl, generics);
1757 Ok(P(ast::ForeignItem { ident, attrs, kind, id: DUMMY_NODE_ID, span, vis, tokens: None }))
1763 attrs: &mut Vec<Attribute>,
1764 is_name_required: fn(&token::Token) -> bool,
1765 ) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
1766 let cfg = ParamCfg { in_assoc_item: true, is_name_required };
1767 let header = self.parse_fn_front_matter()?;
1768 let (ident, decl, generics) = self.parse_fn_sig(&cfg)?;
1769 let sig = FnSig { header, decl };
1770 let body = self.parse_assoc_fn_body(at_end, attrs)?;
1771 Ok((ident, AssocItemKind::Fn(sig, body), generics))
1774 /// Parse the "body" of a method in an associated item definition.
1775 /// This can either be `;` when there's no body,
1776 /// or e.g. a block when the method is a provided one.
1777 fn parse_assoc_fn_body(
1780 attrs: &mut Vec<Attribute>,
1781 ) -> PResult<'a, Option<P<Block>>> {
1782 Ok(match self.token.kind {
1784 debug!("parse_assoc_fn_body(): parsing required method");
1789 token::OpenDelim(token::Brace) => {
1790 debug!("parse_assoc_fn_body(): parsing provided method");
1792 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1793 attrs.extend(inner_attrs.iter().cloned());
1796 token::Interpolated(ref nt) => match **nt {
1797 token::NtBlock(..) => {
1799 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1800 attrs.extend(inner_attrs.iter().cloned());
1803 _ => return self.expected_semi_or_open_brace(),
1805 _ => return self.expected_semi_or_open_brace(),
1809 /// Parses all the "front matter" for a `fn` declaration, up to
1810 /// and including the `fn` keyword:
1814 /// - `const unsafe fn`
1817 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1818 let is_const_fn = self.eat_keyword(kw::Const);
1819 let const_span = self.prev_span;
1820 let asyncness = self.parse_asyncness();
1821 if let IsAsync::Async { .. } = asyncness {
1822 self.ban_async_in_2015(self.prev_span);
1824 let asyncness = respan(self.prev_span, asyncness);
1825 let unsafety = self.parse_unsafety();
1826 let (constness, unsafety, ext) = if is_const_fn {
1827 (respan(const_span, Constness::Const), unsafety, Extern::None)
1829 let ext = self.parse_extern()?;
1830 (respan(self.prev_span, Constness::NotConst), unsafety, ext)
1832 if !self.eat_keyword(kw::Fn) {
1833 // It is possible for `expect_one_of` to recover given the contents of
1834 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1835 // account for this.
1836 if !self.expect_one_of(&[], &[])? {
1840 Ok(FnHeader { constness, unsafety, asyncness, ext })
1843 /// Parse the "signature", including the identifier, parameters, and generics of a function.
1844 fn parse_fn_sig(&mut self, cfg: &ParamCfg) -> PResult<'a, (Ident, P<FnDecl>, Generics)> {
1845 let ident = self.parse_ident()?;
1846 let mut generics = self.parse_generics()?;
1847 let decl = self.parse_fn_decl(cfg, true)?;
1848 generics.where_clause = self.parse_where_clause()?;
1849 Ok((ident, decl, generics))
1852 /// Parses the parameter list and result type of a function declaration.
1853 pub(super) fn parse_fn_decl(
1856 ret_allow_plus: bool,
1857 ) -> PResult<'a, P<FnDecl>> {
1859 inputs: self.parse_fn_params(cfg)?,
1860 output: self.parse_ret_ty(ret_allow_plus, true)?,
1864 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1865 fn parse_fn_params(&mut self, cfg: &ParamCfg) -> PResult<'a, Vec<Param>> {
1866 let mut first_param = true;
1867 // Parse the arguments, starting out with `self` being allowed...
1868 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1869 let param = p.parse_param_general(&cfg, first_param).or_else(|mut e| {
1871 let lo = p.prev_span;
1872 // Skip every token until next possible arg or end.
1873 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1874 // Create a placeholder argument for proper arg count (issue #34264).
1875 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1877 // ...now that we've parsed the first argument, `self` is no longer allowed.
1878 first_param = false;
1881 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1882 self.deduplicate_recovered_params_names(&mut params);
1886 /// Parses a single function parameter.
1888 /// - `self` is syntactically allowed when `first_param` holds.
1889 fn parse_param_general(&mut self, cfg: &ParamCfg, first_param: bool) -> PResult<'a, Param> {
1890 let lo = self.token.span;
1891 let attrs = self.parse_outer_attributes()?;
1893 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1894 if let Some(mut param) = self.parse_self_param()? {
1895 param.attrs = attrs.into();
1896 return if first_param {
1899 self.recover_bad_self_param(param, cfg.in_assoc_item)
1903 let is_name_required = match self.token.kind {
1904 token::DotDotDot => false,
1905 _ => (cfg.is_name_required)(&self.token),
1907 let (pat, ty) = if is_name_required || self.is_named_param() {
1908 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1910 let pat = self.parse_fn_param_pat()?;
1911 if let Err(mut err) = self.expect(&token::Colon) {
1912 return if let Some(ident) = self.parameter_without_type(
1916 first_param && cfg.in_assoc_item,
1920 Ok(dummy_arg(ident))
1926 self.eat_incorrect_doc_comment_for_param_type();
1927 (pat, self.parse_ty_for_param()?)
1929 debug!("parse_param_general ident_to_pat");
1930 let parser_snapshot_before_ty = self.clone();
1931 self.eat_incorrect_doc_comment_for_param_type();
1932 let mut ty = self.parse_ty_for_param();
1934 && self.token != token::Comma
1935 && self.token != token::CloseDelim(token::Paren)
1937 // This wasn't actually a type, but a pattern looking like a type,
1938 // so we are going to rollback and re-parse for recovery.
1939 ty = self.unexpected();
1943 let ident = Ident::new(kw::Invalid, self.prev_span);
1944 let bm = BindingMode::ByValue(Mutability::Not);
1945 let pat = self.mk_pat_ident(ty.span, bm, ident);
1948 // If this is a C-variadic argument and we hit an error, return the error.
1949 Err(err) if self.token == token::DotDotDot => return Err(err),
1950 // Recover from attempting to parse the argument as a type without pattern.
1953 mem::replace(self, parser_snapshot_before_ty);
1954 self.recover_arg_parse()?
1959 let span = lo.to(self.token.span);
1962 attrs: attrs.into(),
1963 id: ast::DUMMY_NODE_ID,
1964 is_placeholder: false,
1971 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1972 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1973 // Extract an identifier *after* having confirmed that the token is one.
1974 let expect_self_ident = |this: &mut Self| {
1975 match this.token.kind {
1976 // Preserve hygienic context.
1977 token::Ident(name, _) => {
1978 let span = this.token.span;
1980 Ident::new(name, span)
1982 _ => unreachable!(),
1985 // Is `self` `n` tokens ahead?
1986 let is_isolated_self = |this: &Self, n| {
1987 this.is_keyword_ahead(n, &[kw::SelfLower])
1988 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1990 // Is `mut self` `n` tokens ahead?
1991 let is_isolated_mut_self =
1992 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1993 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1994 let parse_self_possibly_typed = |this: &mut Self, m| {
1995 let eself_ident = expect_self_ident(this);
1996 let eself_hi = this.prev_span;
1997 let eself = if this.eat(&token::Colon) {
1998 SelfKind::Explicit(this.parse_ty()?, m)
2002 Ok((eself, eself_ident, eself_hi))
2004 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2005 let recover_self_ptr = |this: &mut Self| {
2006 let msg = "cannot pass `self` by raw pointer";
2007 let span = this.token.span;
2008 this.struct_span_err(span, msg).span_label(span, msg).emit();
2010 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
2013 // Parse optional `self` parameter of a method.
2014 // Only a limited set of initial token sequences is considered `self` parameters; anything
2015 // else is parsed as a normal function parameter list, so some lookahead is required.
2016 let eself_lo = self.token.span;
2017 let (eself, eself_ident, eself_hi) = match self.token.kind {
2018 token::BinOp(token::And) => {
2019 let eself = if is_isolated_self(self, 1) {
2022 SelfKind::Region(None, Mutability::Not)
2023 } else if is_isolated_mut_self(self, 1) {
2027 SelfKind::Region(None, Mutability::Mut)
2028 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2031 let lt = self.expect_lifetime();
2032 SelfKind::Region(Some(lt), Mutability::Not)
2033 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2036 let lt = self.expect_lifetime();
2038 SelfKind::Region(Some(lt), Mutability::Mut)
2043 (eself, expect_self_ident(self), self.prev_span)
2046 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2048 recover_self_ptr(self)?
2050 // `*mut self` and `*const self`
2051 token::BinOp(token::Star)
2052 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2056 recover_self_ptr(self)?
2058 // `self` and `self: TYPE`
2059 token::Ident(..) if is_isolated_self(self, 0) => {
2060 parse_self_possibly_typed(self, Mutability::Not)?
2062 // `mut self` and `mut self: TYPE`
2063 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2065 parse_self_possibly_typed(self, Mutability::Mut)?
2067 _ => return Ok(None),
2070 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2071 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2074 fn is_named_param(&self) -> bool {
2075 let offset = match self.token.kind {
2076 token::Interpolated(ref nt) => match **nt {
2077 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2080 token::BinOp(token::And) | token::AndAnd => 1,
2081 _ if self.token.is_keyword(kw::Mut) => 1,
2085 self.look_ahead(offset, |t| t.is_ident())
2086 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2089 fn recover_first_param(&mut self) -> &'static str {
2091 .parse_outer_attributes()
2092 .and_then(|_| self.parse_self_param())
2093 .map_err(|mut e| e.cancel())
2095 Ok(Some(_)) => "method",