1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath};
3 use super::{FollowedByType, Parser, PathStyle};
5 use crate::maybe_whole;
7 use rustc_ast_pretty::pprust;
8 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, PResult, StashKey};
9 use rustc_span::source_map::{self, respan, Span};
10 use rustc_span::symbol::{kw, sym, Symbol};
11 use rustc_span::BytePos;
12 use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
13 use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind};
14 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
15 use syntax::ast::{Constness, Defaultness, Extern, IsAsync, IsAuto, PathSegment, StrLit, Unsafety};
16 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
17 use syntax::ast::{FnHeader, ForeignItem, ForeignItemKind, Mutability, Visibility, VisibilityKind};
20 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
25 pub(super) type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
28 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
29 let attrs = self.parse_outer_attributes()?;
30 self.parse_item_(attrs, true, false)
33 pub(super) fn parse_item_(
35 attrs: Vec<Attribute>,
37 attributes_allowed: bool,
38 ) -> PResult<'a, Option<P<Item>>> {
39 let mut unclosed_delims = vec![];
40 let (ret, tokens) = self.collect_tokens(|this| {
41 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
42 unclosed_delims.append(&mut this.unclosed_delims);
45 self.unclosed_delims.append(&mut unclosed_delims);
47 // Once we've parsed an item and recorded the tokens we got while
48 // parsing we may want to store `tokens` into the item we're about to
49 // return. Note, though, that we specifically didn't capture tokens
50 // related to outer attributes. The `tokens` field here may later be
51 // used with procedural macros to convert this item back into a token
52 // stream, but during expansion we may be removing attributes as we go
55 // If we've got inner attributes then the `tokens` we've got above holds
56 // these inner attributes. If an inner attribute is expanded we won't
57 // actually remove it from the token stream, so we'll just keep yielding
58 // it (bad!). To work around this case for now we just avoid recording
59 // `tokens` if we detect any inner attributes. This should help keep
60 // expansion correct, but we should fix this bug one day!
63 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
64 i.tokens = Some(tokens);
71 /// Parses one of the items allowed by the flags.
72 fn parse_item_implementation(
74 mut attrs: Vec<Attribute>,
76 attributes_allowed: bool,
77 ) -> PResult<'a, Option<P<Item>>> {
78 maybe_whole!(self, NtItem, |item| {
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 if self.eat_keyword(kw::Crate) {
101 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
104 let abi = self.parse_abi();
106 if self.eat_keyword(kw::Fn) {
107 // EXTERN FUNCTION ITEM
108 let fn_span = self.prev_span;
109 let header = FnHeader {
110 unsafety: Unsafety::Normal,
111 asyncness: respan(fn_span, IsAsync::NotAsync),
112 constness: respan(fn_span, Constness::NotConst),
113 ext: Extern::from_abi(abi),
115 return self.parse_item_fn(lo, vis, attrs, header);
116 } else if self.check(&token::OpenDelim(token::Brace)) {
117 return Ok(Some(self.parse_item_foreign_mod(lo, abi, vis, attrs)?));
123 if self.is_static_global() {
126 let m = self.parse_mutability();
127 let info = self.parse_item_const(Some(m))?;
128 return self.mk_item_with_info(attrs, lo, vis, info);
131 if self.eat_keyword(kw::Const) {
132 let const_span = self.prev_span;
133 if [kw::Fn, kw::Unsafe, kw::Extern].iter().any(|k| self.check_keyword(*k)) {
134 // CONST FUNCTION ITEM
135 let unsafety = self.parse_unsafety();
137 if self.check_keyword(kw::Extern) {
138 self.sess.gated_spans.gate(sym::const_extern_fn, lo.to(self.token.span));
140 let ext = self.parse_extern()?;
141 self.expect_keyword(kw::Fn)?;
143 let header = FnHeader {
145 asyncness: respan(const_span, IsAsync::NotAsync),
146 constness: respan(const_span, Constness::Const),
149 return self.parse_item_fn(lo, vis, attrs, header);
153 if self.eat_keyword(kw::Mut) {
154 let prev_span = self.prev_span;
155 self.struct_span_err(prev_span, "const globals cannot be mutable")
156 .span_label(prev_span, "cannot be mutable")
159 "you might want to declare a static instead",
161 Applicability::MaybeIncorrect,
166 let info = self.parse_item_const(None)?;
167 return self.mk_item_with_info(attrs, lo, vis, info);
170 // Parses `async unsafe? fn`.
171 if self.check_keyword(kw::Async) {
172 let async_span = self.token.span;
173 if self.is_keyword_ahead(1, &[kw::Fn]) || self.is_keyword_ahead(2, &[kw::Fn]) {
174 // ASYNC FUNCTION ITEM
175 self.bump(); // `async`
176 let unsafety = self.parse_unsafety(); // `unsafe`?
177 self.expect_keyword(kw::Fn)?; // `fn`
178 let fn_span = self.prev_span;
179 let asyncness = respan(
182 closure_id: DUMMY_NODE_ID,
183 return_impl_trait_id: DUMMY_NODE_ID,
186 self.ban_async_in_2015(async_span);
187 let header = FnHeader {
190 constness: respan(fn_span, Constness::NotConst),
193 return self.parse_item_fn(lo, vis, attrs, header);
197 if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) {
199 self.bump(); // `unsafe`
200 let info = self.parse_item_trait(lo, Unsafety::Unsafe)?;
201 return self.mk_item_with_info(attrs, lo, vis, info);
204 if self.check_keyword(kw::Impl)
205 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
206 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
209 let defaultness = self.parse_defaultness();
210 let unsafety = self.parse_unsafety();
211 self.expect_keyword(kw::Impl)?;
212 let info = self.parse_item_impl(unsafety, defaultness)?;
213 return self.mk_item_with_info(attrs, lo, vis, info);
216 if self.check_keyword(kw::Fn) {
219 let fn_span = self.prev_span;
220 let header = FnHeader {
221 unsafety: Unsafety::Normal,
222 asyncness: respan(fn_span, IsAsync::NotAsync),
223 constness: respan(fn_span, Constness::NotConst),
226 return self.parse_item_fn(lo, vis, attrs, header);
229 if self.check_keyword(kw::Unsafe)
230 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace))
232 // UNSAFE FUNCTION ITEM
233 self.bump(); // `unsafe`
234 // `{` is also expected after `unsafe`; in case of error, include it in the diagnostic.
235 self.check(&token::OpenDelim(token::Brace));
236 let ext = self.parse_extern()?;
237 self.expect_keyword(kw::Fn)?;
238 let fn_span = self.prev_span;
239 let header = FnHeader {
240 unsafety: Unsafety::Unsafe,
241 asyncness: respan(fn_span, IsAsync::NotAsync),
242 constness: respan(fn_span, Constness::NotConst),
245 return self.parse_item_fn(lo, vis, attrs, header);
248 if self.eat_keyword(kw::Mod) {
250 let info = self.parse_item_mod(&attrs[..])?;
251 return self.mk_item_with_info(attrs, lo, vis, info);
254 if self.eat_keyword(kw::Type) {
256 let (ident, ty, generics) = self.parse_type_alias()?;
257 let kind = ItemKind::TyAlias(ty, generics);
258 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
261 if self.eat_keyword(kw::Enum) {
263 let info = self.parse_item_enum()?;
264 return self.mk_item_with_info(attrs, lo, vis, info);
267 if self.check_keyword(kw::Trait)
268 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
271 let info = self.parse_item_trait(lo, Unsafety::Normal)?;
272 return self.mk_item_with_info(attrs, lo, vis, info);
275 if self.eat_keyword(kw::Struct) {
277 let info = self.parse_item_struct()?;
278 return self.mk_item_with_info(attrs, lo, vis, info);
281 if self.is_union_item() {
284 let info = self.parse_item_union()?;
285 return self.mk_item_with_info(attrs, lo, vis, info);
288 if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? {
289 return Ok(Some(macro_def));
292 // Verify whether we have encountered a struct or method definition where the user forgot to
293 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
294 if vis.node.is_pub() && self.check_ident() && self.look_ahead(1, |t| *t != token::Not) {
295 // Space between `pub` keyword and the identifier
298 // ^^^ `sp` points here
299 let sp = self.prev_span.between(self.token.span);
300 let full_sp = self.prev_span.to(self.token.span);
301 let ident_sp = self.token.span;
302 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
303 // possible public struct definition where `struct` was forgotten
304 let ident = self.parse_ident().unwrap();
305 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
306 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
307 err.span_suggestion_short(
311 Applicability::MaybeIncorrect, // speculative
314 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
315 let ident = self.parse_ident().unwrap();
317 let kw_name = self.recover_first_param();
318 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
319 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
320 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
322 ("fn", kw_name, false)
323 } else if self.check(&token::OpenDelim(token::Brace)) {
325 ("fn", kw_name, false)
326 } else if self.check(&token::Colon) {
330 ("fn` or `struct", "function or struct", true)
333 let msg = format!("missing `{}` for {} definition", kw, kw_name);
334 let mut err = self.struct_span_err(sp, &msg);
336 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
338 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
339 err.span_suggestion_short(
343 Applicability::MachineApplicable,
346 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
349 "if you meant to call a macro, try",
350 format!("{}!", snippet),
351 // this is the `ambiguous` conditional branch
352 Applicability::MaybeIncorrect,
356 "if you meant to call a macro, remove the `pub` \
357 and add a trailing `!` after the identifier",
362 } else if self.look_ahead(1, |t| *t == token::Lt) {
363 let ident = self.parse_ident().unwrap();
364 self.eat_to_tokens(&[&token::Gt]);
366 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
367 ("fn", self.recover_first_param(), false)
368 } else if self.check(&token::OpenDelim(token::Brace)) {
369 ("struct", "struct", false)
371 ("fn` or `struct", "function or struct", true)
373 let msg = format!("missing `{}` for {} definition", kw, kw_name);
374 let mut err = self.struct_span_err(sp, &msg);
376 err.span_suggestion_short(
378 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
380 Applicability::MachineApplicable,
386 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis)
389 pub(super) fn mk_item_with_info(
391 attrs: Vec<Attribute>,
395 ) -> PResult<'a, Option<P<Item>>> {
396 let (ident, item, extra_attrs) = info;
397 let span = lo.to(self.prev_span);
398 let attrs = Self::maybe_append(attrs, extra_attrs);
399 Ok(Some(self.mk_item(span, ident, item, vis, attrs)))
402 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
403 if let Some(ref mut rhs) = rhs {
409 /// This is the fall-through for parsing items.
410 fn parse_macro_use_or_failure(
412 attrs: Vec<Attribute>,
413 macros_allowed: bool,
414 attributes_allowed: bool,
416 visibility: Visibility,
417 ) -> PResult<'a, Option<P<Item>>> {
419 && self.token.is_path_start()
420 && !(self.is_async_fn() && self.token.span.rust_2015())
422 // MACRO INVOCATION ITEM
424 let prev_span = self.prev_span;
425 self.complain_if_pub_macro(&visibility.node, prev_span);
428 let path = self.parse_path(PathStyle::Mod)?;
429 self.expect(&token::Not)?;
430 let args = self.parse_mac_args()?;
431 if args.need_semicolon() && !self.eat(&token::Semi) {
432 self.report_invalid_macro_expansion_item();
435 let hi = self.prev_span;
436 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
438 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
439 return Ok(Some(item));
442 // FAILURE TO PARSE ITEM
443 match visibility.node {
444 VisibilityKind::Inherited => {}
445 _ => return Err(self.struct_span_err(self.prev_span, "unmatched visibility `pub`")),
448 if !attributes_allowed && !attrs.is_empty() {
449 self.expected_item_err(&attrs)?;
454 /// Emits an expected-item-after-attributes error.
455 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
456 let message = match attrs.last() {
457 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
458 "expected item after doc comment"
460 _ => "expected item after attributes",
463 let mut err = self.struct_span_err(self.prev_span, message);
464 if attrs.last().unwrap().is_doc_comment() {
465 err.span_label(self.prev_span, "this doc comment doesn't document anything");
470 pub(super) fn is_async_fn(&self) -> bool {
471 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
474 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
475 fn parse_assoc_macro_invoc(
478 vis: Option<&Visibility>,
480 ) -> PResult<'a, Option<Mac>> {
481 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
482 let prev_span = self.prev_span;
483 let path = self.parse_path(PathStyle::Mod)?;
485 if path.segments.len() == 1 {
486 if !self.eat(&token::Not) {
487 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
490 self.expect(&token::Not)?;
493 if let Some(vis) = vis {
494 self.complain_if_pub_macro(&vis.node, prev_span);
499 // eat a matched-delimiter token tree:
500 let args = self.parse_mac_args()?;
501 if args.need_semicolon() {
505 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
511 fn missing_assoc_item_kind_err(
515 ) -> DiagnosticBuilder<'a> {
516 let expected_kinds = if item_type == "extern" {
517 "missing `fn`, `type`, or `static`"
519 "missing `fn`, `type`, or `const`"
522 // Given this code `path(`, it seems like this is not
523 // setting the visibility of a macro invocation, but rather
524 // a mistyped method declaration.
525 // Create a diagnostic pointing out that `fn` is missing.
527 // x | pub path(&self) {
528 // | ^ missing `fn`, `type`, or `const`
530 // ^^ `sp` below will point to this
531 let sp = prev_span.between(self.prev_span);
533 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
534 err.span_label(sp, expected_kinds);
538 /// Parses an implementation item, `impl` keyword is already parsed.
540 /// impl<'a, T> TYPE { /* impl items */ }
541 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
542 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
543 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
545 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
546 /// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
547 /// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
551 defaultness: Defaultness,
552 ) -> PResult<'a, ItemInfo> {
553 // First, parse generic parameters if necessary.
554 let mut generics = if self.choose_generics_over_qpath() {
555 self.parse_generics()?
557 let mut generics = Generics::default();
559 // /\ this is where `generics.span` should point when there are no type params.
560 generics.span = self.prev_span.shrink_to_hi();
564 let constness = if self.eat_keyword(kw::Const) {
565 let span = self.prev_span;
566 self.sess.gated_spans.gate(sym::const_trait_impl, span);
572 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
573 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
575 ast::ImplPolarity::Negative
577 ast::ImplPolarity::Positive
580 // Parse both types and traits as a type, then reinterpret if necessary.
581 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
582 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
584 let span = self.prev_span.between(self.token.span);
585 self.struct_span_err(span, "missing trait in a trait impl").emit();
586 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
591 // If `for` is missing we try to recover.
592 let has_for = self.eat_keyword(kw::For);
593 let missing_for_span = self.prev_span.between(self.token.span);
595 let ty_second = if self.token == token::DotDot {
596 // We need to report this error after `cfg` expansion for compatibility reasons
597 self.bump(); // `..`, do not add it to expected tokens
598 Some(self.mk_ty(self.prev_span, TyKind::Err))
599 } else if has_for || self.token.can_begin_type() {
600 Some(self.parse_ty()?)
605 generics.where_clause = self.parse_where_clause()?;
607 let (impl_items, attrs) = self.parse_impl_body()?;
609 let item_kind = match ty_second {
611 // impl Trait for Type
613 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
614 .span_suggestion_short(
618 Applicability::MachineApplicable,
623 let ty_first = ty_first.into_inner();
624 let path = match ty_first.kind {
625 // This notably includes paths passed through `ty` macro fragments (#46438).
626 TyKind::Path(None, path) => path,
628 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
629 err_path(ty_first.span)
632 let trait_ref = TraitRef { path, ref_id: ty_first.id };
640 of_trait: Some(trait_ref),
660 Ok((Ident::invalid(), item_kind, Some(attrs)))
663 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<P<AssocItem>>, Vec<Attribute>)> {
664 self.expect(&token::OpenDelim(token::Brace))?;
665 let attrs = self.parse_inner_attributes()?;
667 let mut impl_items = Vec::new();
668 while !self.eat(&token::CloseDelim(token::Brace)) {
669 let mut at_end = false;
670 match self.parse_impl_item(&mut at_end) {
671 Ok(impl_item) => impl_items.push(impl_item),
675 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
681 Ok((impl_items, attrs))
684 /// Parses defaultness (i.e., `default` or nothing).
685 fn parse_defaultness(&mut self) -> Defaultness {
686 // `pub` is included for better error messages
687 if self.check_keyword(kw::Default)
688 && self.is_keyword_ahead(
702 self.bump(); // `default`
709 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
710 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
711 // Parse optional `auto` prefix.
712 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
714 self.expect_keyword(kw::Trait)?;
715 let ident = self.parse_ident()?;
716 let mut tps = self.parse_generics()?;
718 // Parse optional colon and supertrait bounds.
719 let had_colon = self.eat(&token::Colon);
720 let span_at_colon = self.prev_span;
722 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
724 let span_before_eq = self.prev_span;
725 if self.eat(&token::Eq) {
726 // It's a trait alias.
728 let span = span_at_colon.to(span_before_eq);
729 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
732 let bounds = self.parse_generic_bounds(None)?;
733 tps.where_clause = self.parse_where_clause()?;
736 let whole_span = lo.to(self.prev_span);
737 if is_auto == IsAuto::Yes {
738 let msg = "trait aliases cannot be `auto`";
739 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
741 if unsafety != Unsafety::Normal {
742 let msg = "trait aliases cannot be `unsafe`";
743 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
746 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
748 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
750 // It's a normal trait.
751 tps.where_clause = self.parse_where_clause()?;
752 self.expect(&token::OpenDelim(token::Brace))?;
753 let mut trait_items = vec![];
754 while !self.eat(&token::CloseDelim(token::Brace)) {
755 if let token::DocComment(_) = self.token.kind {
756 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
761 "found a documentation comment that doesn't document anything",
764 "doc comments must come before what they document, maybe a \
765 comment was intended with `//`?",
772 let mut at_end = false;
773 match self.parse_trait_item(&mut at_end) {
774 Ok(item) => trait_items.push(item),
778 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
784 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
788 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
789 maybe_whole!(self, NtImplItem, |x| x);
790 self.parse_assoc_item(at_end, |_| true)
793 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
794 maybe_whole!(self, NtTraitItem, |x| x);
795 // This is somewhat dubious; We don't want to allow
796 // param names to be left off if there is a definition...
798 // We don't allow param names to be left off in edition 2018.
799 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
802 /// Parses associated items.
806 is_name_required: fn(&token::Token) -> bool,
807 ) -> PResult<'a, P<AssocItem>> {
808 let attrs = self.parse_outer_attributes()?;
809 let mut unclosed_delims = vec![];
810 let (mut item, tokens) = self.collect_tokens(|this| {
811 let item = this.parse_assoc_item_(at_end, attrs, is_name_required);
812 unclosed_delims.append(&mut this.unclosed_delims);
815 self.unclosed_delims.append(&mut unclosed_delims);
816 // See `parse_item` for why this clause is here.
817 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
818 item.tokens = Some(tokens);
823 fn parse_assoc_item_(
826 mut attrs: Vec<Attribute>,
827 is_name_required: fn(&token::Token) -> bool,
828 ) -> PResult<'a, AssocItem> {
829 let lo = self.token.span;
830 let vis = self.parse_visibility(FollowedByType::No)?;
831 let defaultness = self.parse_defaultness();
832 let (name, kind, generics) = if self.eat_keyword(kw::Type) {
833 self.parse_assoc_ty()?
834 } else if self.is_const_item() {
835 self.parse_assoc_const()?
836 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
837 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
839 self.parse_assoc_fn(at_end, &mut attrs, is_name_required)?
844 span: lo.to(self.prev_span),
855 /// Returns `true` if we are looking at `const ID`
856 /// (returns `false` for things like `const fn`, etc.).
857 fn is_const_item(&self) -> bool {
858 self.token.is_keyword(kw::Const) && !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
861 /// This parses the grammar:
863 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
864 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
865 self.expect_keyword(kw::Const)?;
866 let ident = self.parse_ident()?;
867 self.expect(&token::Colon)?;
868 let ty = self.parse_ty()?;
869 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
871 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
874 /// Parses the following grammar:
876 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
877 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
878 let ident = self.parse_ident()?;
879 let mut generics = self.parse_generics()?;
881 // Parse optional colon and param bounds.
883 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
884 generics.where_clause = self.parse_where_clause()?;
886 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
889 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
892 /// Parses a `UseTree`.
895 /// USE_TREE = [`::`] `*` |
896 /// [`::`] `{` USE_TREE_LIST `}` |
898 /// PATH `::` `{` USE_TREE_LIST `}` |
899 /// PATH [`as` IDENT]
901 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
902 let lo = self.token.span;
904 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
905 let kind = if self.check(&token::OpenDelim(token::Brace))
906 || self.check(&token::BinOp(token::Star))
907 || self.is_import_coupler()
909 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
910 let mod_sep_ctxt = self.token.span.ctxt();
911 if self.eat(&token::ModSep) {
914 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
917 self.parse_use_tree_glob_or_nested()?
919 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
920 prefix = self.parse_path(PathStyle::Mod)?;
922 if self.eat(&token::ModSep) {
923 self.parse_use_tree_glob_or_nested()?
925 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
929 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
932 /// Parses `*` or `{...}`.
933 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
934 Ok(if self.eat(&token::BinOp(token::Star)) {
937 UseTreeKind::Nested(self.parse_use_tree_list()?)
941 /// Parses a `UseTreeKind::Nested(list)`.
944 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
946 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
947 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
951 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
952 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
955 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
956 match self.token.kind {
957 token::Ident(name, false) if name == kw::Underscore => {
958 let span = self.token.span;
960 Ok(Ident::new(name, span))
962 _ => self.parse_ident(),
966 /// Parses `extern crate` links.
971 /// extern crate foo;
972 /// extern crate bar as foo;
974 fn parse_item_extern_crate(
977 visibility: Visibility,
978 attrs: Vec<Attribute>,
979 ) -> PResult<'a, P<Item>> {
980 // Accept `extern crate name-like-this` for better diagnostics
981 let orig_name = self.parse_crate_name_with_dashes()?;
982 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
983 (rename, Some(orig_name.name))
989 let span = lo.to(self.prev_span);
990 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
993 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
994 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
995 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
997 let mut ident = if self.token.is_keyword(kw::SelfLower) {
998 self.parse_path_segment_ident()
1002 let mut idents = vec![];
1003 let mut replacement = vec![];
1004 let mut fixed_crate_name = false;
1005 // Accept `extern crate name-like-this` for better diagnostics.
1006 let dash = token::BinOp(token::BinOpToken::Minus);
1007 if self.token == dash {
1008 // Do not include `-` as part of the expected tokens list.
1009 while self.eat(&dash) {
1010 fixed_crate_name = true;
1011 replacement.push((self.prev_span, "_".to_string()));
1012 idents.push(self.parse_ident()?);
1015 if fixed_crate_name {
1016 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1017 let mut fixed_name = format!("{}", ident.name);
1018 for part in idents {
1019 fixed_name.push_str(&format!("_{}", part.name));
1021 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1023 self.struct_span_err(fixed_name_sp, error_msg)
1024 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1025 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1031 /// Parses `extern` for foreign ABIs modules.
1033 /// `extern` is expected to have been
1034 /// consumed before calling this method.
1038 /// ```ignore (only-for-syntax-highlight)
1042 fn parse_item_foreign_mod(
1045 abi: Option<StrLit>,
1046 visibility: Visibility,
1047 mut attrs: Vec<Attribute>,
1048 ) -> PResult<'a, P<Item>> {
1049 self.expect(&token::OpenDelim(token::Brace))?;
1051 attrs.extend(self.parse_inner_attributes()?);
1053 let mut foreign_items = vec![];
1054 while !self.eat(&token::CloseDelim(token::Brace)) {
1055 foreign_items.push(self.parse_foreign_item()?);
1058 let prev_span = self.prev_span;
1059 let m = ast::ForeignMod { abi, items: foreign_items };
1060 let invalid = Ident::invalid();
1061 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
1064 /// Parses a foreign item.
1065 pub fn parse_foreign_item(&mut self) -> PResult<'a, P<ForeignItem>> {
1066 maybe_whole!(self, NtForeignItem, |ni| ni);
1068 let attrs = self.parse_outer_attributes()?;
1069 let lo = self.token.span;
1070 let visibility = self.parse_visibility(FollowedByType::No)?;
1072 // FOREIGN TYPE ITEM
1073 if self.check_keyword(kw::Type) {
1074 return self.parse_item_foreign_type(visibility, lo, attrs);
1077 // FOREIGN STATIC ITEM
1078 if self.is_static_global() {
1079 self.bump(); // `static`
1080 return self.parse_item_foreign_static(visibility, lo, attrs);
1083 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
1084 if self.is_kw_followed_by_ident(kw::Const) {
1085 self.bump(); // `const`
1086 self.struct_span_err(self.prev_span, "extern items cannot be `const`")
1089 "try using a static value",
1090 "static".to_owned(),
1091 Applicability::MachineApplicable,
1094 return self.parse_item_foreign_static(visibility, lo, attrs);
1097 // FOREIGN FUNCTION ITEM
1098 const MAY_INTRODUCE_FN: &[Symbol] = &[kw::Const, kw::Async, kw::Unsafe, kw::Extern, kw::Fn];
1099 if MAY_INTRODUCE_FN.iter().any(|&kw| self.check_keyword(kw)) {
1100 return self.parse_item_foreign_fn(visibility, lo, attrs);
1103 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
1104 Some(mac) => Ok(P(ForeignItem {
1105 ident: Ident::invalid(),
1106 span: lo.to(self.prev_span),
1110 kind: ForeignItemKind::Macro(mac),
1114 if !attrs.is_empty() {
1115 self.expected_item_err(&attrs)?;
1123 /// Parses a static item from a foreign module.
1124 /// Assumes that the `static` keyword is already parsed.
1125 fn parse_item_foreign_static(
1127 vis: ast::Visibility,
1129 attrs: Vec<Attribute>,
1130 ) -> PResult<'a, P<ForeignItem>> {
1131 let mutbl = self.parse_mutability();
1132 let ident = self.parse_ident()?;
1133 self.expect(&token::Colon)?;
1134 let ty = self.parse_ty()?;
1135 let hi = self.token.span;
1136 self.expect_semi()?;
1140 kind: ForeignItemKind::Static(ty, mutbl),
1148 /// Parses a type from a foreign module.
1149 fn parse_item_foreign_type(
1151 vis: ast::Visibility,
1153 attrs: Vec<Attribute>,
1154 ) -> PResult<'a, P<ForeignItem>> {
1155 self.expect_keyword(kw::Type)?;
1157 let ident = self.parse_ident()?;
1158 let hi = self.token.span;
1159 self.expect_semi()?;
1160 Ok(P(ast::ForeignItem {
1163 kind: ForeignItemKind::Ty,
1171 fn is_static_global(&mut self) -> bool {
1172 if self.check_keyword(kw::Static) {
1173 // Check if this could be a closure.
1174 !self.look_ahead(1, |token| {
1175 if token.is_keyword(kw::Move) {
1179 token::BinOp(token::Or) | token::OrOr => true,
1188 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1189 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1191 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1192 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1193 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1195 // Parse the type of a `const` or `static mut?` item.
1196 // That is, the `":" $ty` fragment.
1197 let ty = if self.token == token::Eq {
1198 self.recover_missing_const_type(id, m)
1200 // Not `=` so expect `":"" $ty` as usual.
1201 self.expect(&token::Colon)?;
1205 self.expect(&token::Eq)?;
1206 let e = self.parse_expr()?;
1207 self.expect_semi()?;
1208 let item = match m {
1209 Some(m) => ItemKind::Static(ty, m, e),
1210 None => ItemKind::Const(ty, e),
1212 Ok((id, item, None))
1215 /// We were supposed to parse `:` but instead, we're already at `=`.
1216 /// This means that the type is missing.
1217 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1218 // Construct the error and stash it away with the hope
1219 // that typeck will later enrich the error with a type.
1220 let kind = match m {
1221 Some(Mutability::Mut) => "static mut",
1222 Some(Mutability::Not) => "static",
1225 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1226 err.span_suggestion(
1228 "provide a type for the item",
1229 format!("{}: <type>", id),
1230 Applicability::HasPlaceholders,
1232 err.stash(id.span, StashKey::ItemNoType);
1234 // The user intended that the type be inferred,
1235 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1236 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1239 /// Parses the grammar:
1240 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1241 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1242 let ident = self.parse_ident()?;
1243 let mut tps = self.parse_generics()?;
1244 tps.where_clause = self.parse_where_clause()?;
1245 self.expect(&token::Eq)?;
1246 let ty = self.parse_ty()?;
1247 self.expect_semi()?;
1248 Ok((ident, ty, tps))
1251 /// Parses an enum declaration.
1252 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1253 let id = self.parse_ident()?;
1254 let mut generics = self.parse_generics()?;
1255 generics.where_clause = self.parse_where_clause()?;
1258 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1259 self.recover_stmt();
1263 let enum_definition =
1264 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1265 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1268 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1269 let variant_attrs = self.parse_outer_attributes()?;
1270 let vlo = self.token.span;
1272 let vis = self.parse_visibility(FollowedByType::No)?;
1273 if !self.recover_nested_adt_item(kw::Enum)? {
1276 let ident = self.parse_ident()?;
1278 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1279 // Parse a struct variant.
1280 let (fields, recovered) = self.parse_record_struct_body()?;
1281 VariantData::Struct(fields, recovered)
1282 } else if self.check(&token::OpenDelim(token::Paren)) {
1283 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1285 VariantData::Unit(DUMMY_NODE_ID)
1289 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1291 let vr = ast::Variant {
1295 attrs: variant_attrs,
1298 span: vlo.to(self.prev_span),
1299 is_placeholder: false,
1305 /// Parses `struct Foo { ... }`.
1306 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1307 let class_name = self.parse_ident()?;
1309 let mut generics = self.parse_generics()?;
1311 // There is a special case worth noting here, as reported in issue #17904.
1312 // If we are parsing a tuple struct it is the case that the where clause
1313 // should follow the field list. Like so:
1315 // struct Foo<T>(T) where T: Copy;
1317 // If we are parsing a normal record-style struct it is the case
1318 // that the where clause comes before the body, and after the generics.
1319 // So if we look ahead and see a brace or a where-clause we begin
1320 // parsing a record style struct.
1322 // Otherwise if we look ahead and see a paren we parse a tuple-style
1325 let vdata = if self.token.is_keyword(kw::Where) {
1326 generics.where_clause = self.parse_where_clause()?;
1327 if self.eat(&token::Semi) {
1328 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1329 VariantData::Unit(DUMMY_NODE_ID)
1331 // If we see: `struct Foo<T> where T: Copy { ... }`
1332 let (fields, recovered) = self.parse_record_struct_body()?;
1333 VariantData::Struct(fields, recovered)
1335 // No `where` so: `struct Foo<T>;`
1336 } else if self.eat(&token::Semi) {
1337 VariantData::Unit(DUMMY_NODE_ID)
1338 // Record-style struct definition
1339 } else if self.token == token::OpenDelim(token::Brace) {
1340 let (fields, recovered) = self.parse_record_struct_body()?;
1341 VariantData::Struct(fields, recovered)
1342 // Tuple-style struct definition with optional where-clause.
1343 } else if self.token == token::OpenDelim(token::Paren) {
1344 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1345 generics.where_clause = self.parse_where_clause()?;
1346 self.expect_semi()?;
1349 let token_str = super::token_descr(&self.token);
1351 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1354 let mut err = self.struct_span_err(self.token.span, msg);
1355 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1359 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1362 /// Parses `union Foo { ... }`.
1363 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1364 let class_name = self.parse_ident()?;
1366 let mut generics = self.parse_generics()?;
1368 let vdata = if self.token.is_keyword(kw::Where) {
1369 generics.where_clause = self.parse_where_clause()?;
1370 let (fields, recovered) = self.parse_record_struct_body()?;
1371 VariantData::Struct(fields, recovered)
1372 } else if self.token == token::OpenDelim(token::Brace) {
1373 let (fields, recovered) = self.parse_record_struct_body()?;
1374 VariantData::Struct(fields, recovered)
1376 let token_str = super::token_descr(&self.token);
1377 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1378 let mut err = self.struct_span_err(self.token.span, msg);
1379 err.span_label(self.token.span, "expected `where` or `{` after union name");
1383 Ok((class_name, ItemKind::Union(vdata, generics), None))
1386 pub(super) fn is_union_item(&self) -> bool {
1387 self.token.is_keyword(kw::Union)
1388 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1391 fn parse_record_struct_body(
1393 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1394 let mut fields = Vec::new();
1395 let mut recovered = false;
1396 if self.eat(&token::OpenDelim(token::Brace)) {
1397 while self.token != token::CloseDelim(token::Brace) {
1398 let field = self.parse_struct_decl_field().map_err(|e| {
1399 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1404 Ok(field) => fields.push(field),
1411 self.eat(&token::CloseDelim(token::Brace));
1413 let token_str = super::token_descr(&self.token);
1414 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1415 let mut err = self.struct_span_err(self.token.span, msg);
1416 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1420 Ok((fields, recovered))
1423 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1424 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1425 // Unit like structs are handled in parse_item_struct function
1426 self.parse_paren_comma_seq(|p| {
1427 let attrs = p.parse_outer_attributes()?;
1428 let lo = p.token.span;
1429 let vis = p.parse_visibility(FollowedByType::Yes)?;
1430 let ty = p.parse_ty()?;
1432 span: lo.to(ty.span),
1438 is_placeholder: false,
1444 /// Parses an element of a struct declaration.
1445 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1446 let attrs = self.parse_outer_attributes()?;
1447 let lo = self.token.span;
1448 let vis = self.parse_visibility(FollowedByType::No)?;
1449 self.parse_single_struct_field(lo, vis, attrs)
1452 /// Parses a structure field declaration.
1453 fn parse_single_struct_field(
1457 attrs: Vec<Attribute>,
1458 ) -> PResult<'a, StructField> {
1459 let mut seen_comma: bool = false;
1460 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1461 if self.token == token::Comma {
1464 match self.token.kind {
1468 token::CloseDelim(token::Brace) => {}
1469 token::DocComment(_) => {
1470 let previous_span = self.prev_span;
1471 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1472 self.bump(); // consume the doc comment
1473 let comma_after_doc_seen = self.eat(&token::Comma);
1474 // `seen_comma` is always false, because we are inside doc block
1475 // condition is here to make code more readable
1476 if seen_comma == false && comma_after_doc_seen == true {
1479 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1482 if seen_comma == false {
1483 let sp = self.sess.source_map().next_point(previous_span);
1484 err.span_suggestion(
1486 "missing comma here",
1488 Applicability::MachineApplicable,
1495 let sp = self.prev_span.shrink_to_hi();
1496 let mut err = self.struct_span_err(
1498 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1500 if self.token.is_ident() {
1501 // This is likely another field; emit the diagnostic and keep going
1502 err.span_suggestion(
1504 "try adding a comma",
1506 Applicability::MachineApplicable,
1517 /// Parses a structure field.
1518 fn parse_name_and_ty(
1522 attrs: Vec<Attribute>,
1523 ) -> PResult<'a, StructField> {
1524 let name = self.parse_ident()?;
1525 self.expect(&token::Colon)?;
1526 let ty = self.parse_ty()?;
1528 span: lo.to(self.prev_span),
1534 is_placeholder: false,
1538 pub(super) fn eat_macro_def(
1540 attrs: &[Attribute],
1543 ) -> PResult<'a, Option<P<Item>>> {
1544 let (ident, def) = if self.eat_keyword(kw::Macro) {
1545 let ident = self.parse_ident()?;
1546 let body = if self.check(&token::OpenDelim(token::Brace)) {
1547 self.parse_mac_args()?
1548 } else if self.check(&token::OpenDelim(token::Paren)) {
1549 let params = self.parse_token_tree();
1550 let pspan = params.span();
1551 let body = if self.check(&token::OpenDelim(token::Brace)) {
1552 self.parse_token_tree()
1554 return self.unexpected();
1556 let bspan = body.span();
1557 let tokens = TokenStream::new(vec![
1559 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1562 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1563 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1565 return self.unexpected();
1568 (ident, ast::MacroDef { body, legacy: false })
1569 } else if self.check_keyword(sym::macro_rules)
1570 && self.look_ahead(1, |t| *t == token::Not)
1571 && self.look_ahead(2, |t| t.is_ident())
1573 let prev_span = self.prev_span;
1574 self.complain_if_pub_macro(&vis.node, prev_span);
1578 let ident = self.parse_ident()?;
1579 let body = self.parse_mac_args()?;
1580 if body.need_semicolon() && !self.eat(&token::Semi) {
1581 self.report_invalid_macro_expansion_item();
1584 (ident, ast::MacroDef { body, legacy: true })
1589 let span = lo.to(self.prev_span);
1592 self.sess.gated_spans.gate(sym::decl_macro, span);
1595 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1598 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1600 VisibilityKind::Inherited => {}
1602 let mut err = if self.token.is_keyword(sym::macro_rules) {
1604 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1605 err.span_suggestion(
1607 "try exporting the macro",
1608 "#[macro_export]".to_owned(),
1609 Applicability::MaybeIncorrect, // speculative
1614 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1615 err.help("try adjusting the macro to put `pub` inside the invocation");
1623 fn report_invalid_macro_expansion_item(&self) {
1624 let has_close_delim = self
1627 .span_to_snippet(self.prev_span)
1628 .map(|s| s.ends_with(")") || s.ends_with("]"))
1631 let mut err = self.struct_span_err(
1633 "macros that expand to items must be delimited with braces or followed by a semicolon",
1636 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1637 if has_close_delim {
1638 err.multipart_suggestion(
1639 "change the delimiters to curly braces",
1641 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1642 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1644 Applicability::MaybeIncorrect,
1647 err.span_suggestion(
1649 "change the delimiters to curly braces",
1650 " { /* items */ }".to_string(),
1651 Applicability::HasPlaceholders,
1655 err.span_suggestion(
1656 self.prev_span.shrink_to_hi(),
1659 Applicability::MaybeIncorrect,
1664 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1665 /// it is, we try to parse the item and report error about nested types.
1666 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1667 if (self.token.is_keyword(kw::Enum)
1668 || self.token.is_keyword(kw::Struct)
1669 || self.token.is_keyword(kw::Union))
1670 && self.look_ahead(1, |t| t.is_ident())
1672 let kw_token = self.token.clone();
1673 let kw_str = pprust::token_to_string(&kw_token);
1674 let item = self.parse_item()?;
1676 self.struct_span_err(
1678 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1682 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1684 Applicability::MaybeIncorrect,
1687 // We successfully parsed the item but we must inform the caller about nested problem.
1699 attrs: Vec<Attribute>,
1701 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1705 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1706 pub(super) struct ParamCfg {
1707 /// `is_name_required` decides if, per-parameter,
1708 /// the parameter must have a pattern or just a type.
1709 pub is_name_required: fn(&token::Token) -> bool,
1712 /// Parsing of functions and methods.
1713 impl<'a> Parser<'a> {
1714 /// Parses an item-position function declaration.
1719 mut attrs: Vec<Attribute>,
1721 ) -> PResult<'a, Option<P<Item>>> {
1722 let cfg = ParamCfg { is_name_required: |_| true };
1723 let (ident, decl, generics) = self.parse_fn_sig(&cfg)?;
1724 let body = self.parse_fn_body(&mut false, &mut attrs)?;
1725 let kind = ItemKind::Fn(FnSig { decl, header }, generics, body);
1726 self.mk_item_with_info(attrs, lo, vis, (ident, kind, None))
1729 /// Parses a function declaration from a foreign module.
1730 fn parse_item_foreign_fn(
1732 vis: ast::Visibility,
1734 mut attrs: Vec<Attribute>,
1735 ) -> PResult<'a, P<ForeignItem>> {
1736 let cfg = ParamCfg { is_name_required: |_| true };
1737 let header = self.parse_fn_front_matter()?;
1738 let (ident, decl, generics) = self.parse_fn_sig(&cfg)?;
1739 let body = self.parse_fn_body(&mut false, &mut attrs)?;
1740 let kind = ForeignItemKind::Fn(FnSig { header, decl }, generics, body);
1741 let span = lo.to(self.prev_span);
1742 Ok(P(ast::ForeignItem { ident, attrs, kind, id: DUMMY_NODE_ID, span, vis, tokens: None }))
1748 attrs: &mut Vec<Attribute>,
1749 is_name_required: fn(&token::Token) -> bool,
1750 ) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
1751 let header = self.parse_fn_front_matter()?;
1752 let (ident, decl, generics) = self.parse_fn_sig(&&ParamCfg { is_name_required })?;
1753 let body = self.parse_fn_body(at_end, attrs)?;
1754 Ok((ident, AssocItemKind::Fn(FnSig { header, decl }, body), generics))
1757 /// Parse the "body" of a function.
1758 /// This can either be `;` when there's no body,
1759 /// or e.g. a block when the function is a provided one.
1763 attrs: &mut Vec<Attribute>,
1764 ) -> PResult<'a, Option<P<Block>>> {
1765 let (inner_attrs, body) = match self.token.kind {
1770 token::OpenDelim(token::Brace) => {
1771 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1774 token::Interpolated(ref nt) => match **nt {
1775 token::NtBlock(..) => {
1776 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1779 _ => return self.expected_semi_or_open_brace(),
1781 _ => return self.expected_semi_or_open_brace(),
1783 attrs.extend(inner_attrs);
1788 /// Parses all the "front matter" for a `fn` declaration, up to
1789 /// and including the `fn` keyword:
1793 /// - `const unsafe fn`
1796 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1797 let is_const_fn = self.eat_keyword(kw::Const);
1798 let const_span = self.prev_span;
1799 let asyncness = self.parse_asyncness();
1800 if let IsAsync::Async { .. } = asyncness {
1801 self.ban_async_in_2015(self.prev_span);
1803 let asyncness = respan(self.prev_span, asyncness);
1804 let unsafety = self.parse_unsafety();
1805 let (constness, unsafety, ext) = if is_const_fn {
1806 (respan(const_span, Constness::Const), unsafety, Extern::None)
1808 let ext = self.parse_extern()?;
1809 (respan(self.prev_span, Constness::NotConst), unsafety, ext)
1811 if !self.eat_keyword(kw::Fn) {
1812 // It is possible for `expect_one_of` to recover given the contents of
1813 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1814 // account for this.
1815 if !self.expect_one_of(&[], &[])? {
1819 Ok(FnHeader { constness, unsafety, asyncness, ext })
1822 /// Parse the "signature", including the identifier, parameters, and generics of a function.
1823 fn parse_fn_sig(&mut self, cfg: &ParamCfg) -> PResult<'a, (Ident, P<FnDecl>, Generics)> {
1824 let ident = self.parse_ident()?;
1825 let mut generics = self.parse_generics()?;
1826 let decl = self.parse_fn_decl(cfg, AllowPlus::Yes)?;
1827 generics.where_clause = self.parse_where_clause()?;
1828 Ok((ident, decl, generics))
1831 /// Parses the parameter list and result type of a function declaration.
1832 pub(super) fn parse_fn_decl(
1835 ret_allow_plus: AllowPlus,
1836 ) -> PResult<'a, P<FnDecl>> {
1838 inputs: self.parse_fn_params(cfg)?,
1839 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1843 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1844 fn parse_fn_params(&mut self, cfg: &ParamCfg) -> PResult<'a, Vec<Param>> {
1845 let mut first_param = true;
1846 // Parse the arguments, starting out with `self` being allowed...
1847 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1848 let param = p.parse_param_general(&cfg, first_param).or_else(|mut e| {
1850 let lo = p.prev_span;
1851 // Skip every token until next possible arg or end.
1852 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1853 // Create a placeholder argument for proper arg count (issue #34264).
1854 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1856 // ...now that we've parsed the first argument, `self` is no longer allowed.
1857 first_param = false;
1860 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1861 self.deduplicate_recovered_params_names(&mut params);
1865 /// Parses a single function parameter.
1867 /// - `self` is syntactically allowed when `first_param` holds.
1868 fn parse_param_general(&mut self, cfg: &ParamCfg, first_param: bool) -> PResult<'a, Param> {
1869 let lo = self.token.span;
1870 let attrs = self.parse_outer_attributes()?;
1872 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1873 if let Some(mut param) = self.parse_self_param()? {
1874 param.attrs = attrs.into();
1875 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1878 let is_name_required = match self.token.kind {
1879 token::DotDotDot => false,
1880 _ => (cfg.is_name_required)(&self.token),
1882 let (pat, ty) = if is_name_required || self.is_named_param() {
1883 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1885 let pat = self.parse_fn_param_pat()?;
1886 if let Err(mut err) = self.expect(&token::Colon) {
1887 return if let Some(ident) =
1888 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1891 Ok(dummy_arg(ident))
1897 self.eat_incorrect_doc_comment_for_param_type();
1898 (pat, self.parse_ty_for_param()?)
1900 debug!("parse_param_general ident_to_pat");
1901 let parser_snapshot_before_ty = self.clone();
1902 self.eat_incorrect_doc_comment_for_param_type();
1903 let mut ty = self.parse_ty_for_param();
1905 && self.token != token::Comma
1906 && self.token != token::CloseDelim(token::Paren)
1908 // This wasn't actually a type, but a pattern looking like a type,
1909 // so we are going to rollback and re-parse for recovery.
1910 ty = self.unexpected();
1914 let ident = Ident::new(kw::Invalid, self.prev_span);
1915 let bm = BindingMode::ByValue(Mutability::Not);
1916 let pat = self.mk_pat_ident(ty.span, bm, ident);
1919 // If this is a C-variadic argument and we hit an error, return the error.
1920 Err(err) if self.token == token::DotDotDot => return Err(err),
1921 // Recover from attempting to parse the argument as a type without pattern.
1924 mem::replace(self, parser_snapshot_before_ty);
1925 self.recover_arg_parse()?
1930 let span = lo.to(self.token.span);
1933 attrs: attrs.into(),
1934 id: ast::DUMMY_NODE_ID,
1935 is_placeholder: false,
1942 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1943 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1944 // Extract an identifier *after* having confirmed that the token is one.
1945 let expect_self_ident = |this: &mut Self| {
1946 match this.token.kind {
1947 // Preserve hygienic context.
1948 token::Ident(name, _) => {
1949 let span = this.token.span;
1951 Ident::new(name, span)
1953 _ => unreachable!(),
1956 // Is `self` `n` tokens ahead?
1957 let is_isolated_self = |this: &Self, n| {
1958 this.is_keyword_ahead(n, &[kw::SelfLower])
1959 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1961 // Is `mut self` `n` tokens ahead?
1962 let is_isolated_mut_self =
1963 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1964 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1965 let parse_self_possibly_typed = |this: &mut Self, m| {
1966 let eself_ident = expect_self_ident(this);
1967 let eself_hi = this.prev_span;
1968 let eself = if this.eat(&token::Colon) {
1969 SelfKind::Explicit(this.parse_ty()?, m)
1973 Ok((eself, eself_ident, eself_hi))
1975 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1976 let recover_self_ptr = |this: &mut Self| {
1977 let msg = "cannot pass `self` by raw pointer";
1978 let span = this.token.span;
1979 this.struct_span_err(span, msg).span_label(span, msg).emit();
1981 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1984 // Parse optional `self` parameter of a method.
1985 // Only a limited set of initial token sequences is considered `self` parameters; anything
1986 // else is parsed as a normal function parameter list, so some lookahead is required.
1987 let eself_lo = self.token.span;
1988 let (eself, eself_ident, eself_hi) = match self.token.kind {
1989 token::BinOp(token::And) => {
1990 let eself = if is_isolated_self(self, 1) {
1993 SelfKind::Region(None, Mutability::Not)
1994 } else if is_isolated_mut_self(self, 1) {
1998 SelfKind::Region(None, Mutability::Mut)
1999 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2002 let lt = self.expect_lifetime();
2003 SelfKind::Region(Some(lt), Mutability::Not)
2004 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2007 let lt = self.expect_lifetime();
2009 SelfKind::Region(Some(lt), Mutability::Mut)
2014 (eself, expect_self_ident(self), self.prev_span)
2017 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2019 recover_self_ptr(self)?
2021 // `*mut self` and `*const self`
2022 token::BinOp(token::Star)
2023 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2027 recover_self_ptr(self)?
2029 // `self` and `self: TYPE`
2030 token::Ident(..) if is_isolated_self(self, 0) => {
2031 parse_self_possibly_typed(self, Mutability::Not)?
2033 // `mut self` and `mut self: TYPE`
2034 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2036 parse_self_possibly_typed(self, Mutability::Mut)?
2038 _ => return Ok(None),
2041 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2042 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2045 fn is_named_param(&self) -> bool {
2046 let offset = match self.token.kind {
2047 token::Interpolated(ref nt) => match **nt {
2048 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2051 token::BinOp(token::And) | token::AndAnd => 1,
2052 _ if self.token.is_keyword(kw::Mut) => 1,
2056 self.look_ahead(offset, |t| t.is_ident())
2057 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2060 fn recover_first_param(&mut self) -> &'static str {
2062 .parse_outer_attributes()
2063 .and_then(|_| self.parse_self_param())
2064 .map_err(|mut e| e.cancel())
2066 Ok(Some(_)) => "method",