1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::{FollowedByType, Parser, PathStyle};
4 use crate::maybe_whole;
6 use rustc_ast_pretty::pprust;
7 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, PResult, StashKey};
8 use rustc_span::source_map::{self, respan, Span};
9 use rustc_span::symbol::{kw, sym, Symbol};
10 use rustc_span::BytePos;
11 use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
12 use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind};
13 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
14 use syntax::ast::{Constness, Defaultness, Extern, IsAsync, IsAuto, PathSegment, StrLit, Unsafety};
15 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
16 use syntax::ast::{FnHeader, ForeignItem, ForeignItemKind, Mutability, Visibility, VisibilityKind};
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 mut attrs: Vec<Attribute>,
75 attributes_allowed: bool,
76 ) -> PResult<'a, Option<P<Item>>> {
77 maybe_whole!(self, NtItem, |item| {
79 mem::swap(&mut item.attrs, &mut attrs);
80 item.attrs.extend(attrs);
84 let lo = self.token.span;
86 let vis = self.parse_visibility(FollowedByType::No)?;
88 if self.eat_keyword(kw::Use) {
90 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
93 let span = lo.to(self.prev_span);
94 let item = self.mk_item(span, Ident::invalid(), item_, vis, attrs);
95 return Ok(Some(item));
98 if self.eat_keyword(kw::Extern) {
99 let extern_sp = self.prev_span;
100 if self.eat_keyword(kw::Crate) {
101 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
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, extern_sp)?));
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>,
1049 ) -> PResult<'a, P<Item>> {
1050 self.expect(&token::OpenDelim(token::Brace))?;
1052 attrs.extend(self.parse_inner_attributes()?);
1054 let mut foreign_items = vec![];
1055 while !self.eat(&token::CloseDelim(token::Brace)) {
1056 foreign_items.push(self.parse_foreign_item(extern_sp)?);
1059 let prev_span = self.prev_span;
1060 let m = ast::ForeignMod { abi, items: foreign_items };
1061 let invalid = Ident::invalid();
1062 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
1065 /// Parses a foreign item.
1066 pub fn parse_foreign_item(&mut self, extern_sp: Span) -> PResult<'a, P<ForeignItem>> {
1067 maybe_whole!(self, NtForeignItem, |ni| ni);
1069 let attrs = self.parse_outer_attributes()?;
1070 let lo = self.token.span;
1071 let visibility = self.parse_visibility(FollowedByType::No)?;
1073 // FOREIGN STATIC ITEM
1074 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
1075 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
1076 if self.token.is_keyword(kw::Const) {
1078 self.struct_span_err(self.token.span, "extern items cannot be `const`");
1080 // The user wrote 'const fn'
1081 if self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) {
1085 // Consume `unsafe` if present, since `extern` blocks
1086 // don't allow it. This will leave behind a plain 'fn'
1087 self.eat_keyword(kw::Unsafe);
1088 // Treat 'const fn` as a plain `fn` for error recovery purposes.
1089 // We've already emitted an error, so compilation is guaranteed
1091 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
1093 err.span_suggestion(
1095 "try using a static value",
1096 "static".to_owned(),
1097 Applicability::MachineApplicable,
1101 self.bump(); // `static` or `const`
1102 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
1104 // FOREIGN FUNCTION ITEM
1105 if self.check_keyword(kw::Fn) {
1106 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
1108 // FOREIGN TYPE ITEM
1109 if self.check_keyword(kw::Type) {
1110 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
1113 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
1114 Some(mac) => Ok(P(ForeignItem {
1115 ident: Ident::invalid(),
1116 span: lo.to(self.prev_span),
1120 kind: ForeignItemKind::Macro(mac),
1124 if !attrs.is_empty() {
1125 self.expected_item_err(&attrs)?;
1133 /// Parses a static item from a foreign module.
1134 /// Assumes that the `static` keyword is already parsed.
1135 fn parse_item_foreign_static(
1137 vis: ast::Visibility,
1139 attrs: Vec<Attribute>,
1140 ) -> PResult<'a, P<ForeignItem>> {
1141 let mutbl = self.parse_mutability();
1142 let ident = self.parse_ident()?;
1143 self.expect(&token::Colon)?;
1144 let ty = self.parse_ty()?;
1145 let hi = self.token.span;
1146 self.expect_semi()?;
1150 kind: ForeignItemKind::Static(ty, mutbl),
1158 /// Parses a type from a foreign module.
1159 fn parse_item_foreign_type(
1161 vis: ast::Visibility,
1163 attrs: Vec<Attribute>,
1164 ) -> PResult<'a, P<ForeignItem>> {
1165 self.expect_keyword(kw::Type)?;
1167 let ident = self.parse_ident()?;
1168 let hi = self.token.span;
1169 self.expect_semi()?;
1170 Ok(P(ast::ForeignItem {
1173 kind: ForeignItemKind::Ty,
1181 fn is_static_global(&mut self) -> bool {
1182 if self.check_keyword(kw::Static) {
1183 // Check if this could be a closure.
1184 !self.look_ahead(1, |token| {
1185 if token.is_keyword(kw::Move) {
1189 token::BinOp(token::Or) | token::OrOr => true,
1198 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1199 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1201 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1202 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1203 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1205 // Parse the type of a `const` or `static mut?` item.
1206 // That is, the `":" $ty` fragment.
1207 let ty = if self.token == token::Eq {
1208 self.recover_missing_const_type(id, m)
1210 // Not `=` so expect `":"" $ty` as usual.
1211 self.expect(&token::Colon)?;
1215 self.expect(&token::Eq)?;
1216 let e = self.parse_expr()?;
1217 self.expect_semi()?;
1218 let item = match m {
1219 Some(m) => ItemKind::Static(ty, m, e),
1220 None => ItemKind::Const(ty, e),
1222 Ok((id, item, None))
1225 /// We were supposed to parse `:` but instead, we're already at `=`.
1226 /// This means that the type is missing.
1227 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1228 // Construct the error and stash it away with the hope
1229 // that typeck will later enrich the error with a type.
1230 let kind = match m {
1231 Some(Mutability::Mut) => "static mut",
1232 Some(Mutability::Not) => "static",
1235 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1236 err.span_suggestion(
1238 "provide a type for the item",
1239 format!("{}: <type>", id),
1240 Applicability::HasPlaceholders,
1242 err.stash(id.span, StashKey::ItemNoType);
1244 // The user intended that the type be inferred,
1245 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1246 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1249 /// Parses the grammar:
1250 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1251 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1252 let ident = self.parse_ident()?;
1253 let mut tps = self.parse_generics()?;
1254 tps.where_clause = self.parse_where_clause()?;
1255 self.expect(&token::Eq)?;
1256 let ty = self.parse_ty()?;
1257 self.expect_semi()?;
1258 Ok((ident, ty, tps))
1261 /// Parses an enum declaration.
1262 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1263 let id = self.parse_ident()?;
1264 let mut generics = self.parse_generics()?;
1265 generics.where_clause = self.parse_where_clause()?;
1268 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1269 self.recover_stmt();
1273 let enum_definition =
1274 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1275 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1278 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1279 let variant_attrs = self.parse_outer_attributes()?;
1280 let vlo = self.token.span;
1282 let vis = self.parse_visibility(FollowedByType::No)?;
1283 if !self.recover_nested_adt_item(kw::Enum)? {
1286 let ident = self.parse_ident()?;
1288 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1289 // Parse a struct variant.
1290 let (fields, recovered) = self.parse_record_struct_body()?;
1291 VariantData::Struct(fields, recovered)
1292 } else if self.check(&token::OpenDelim(token::Paren)) {
1293 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1295 VariantData::Unit(DUMMY_NODE_ID)
1299 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1301 let vr = ast::Variant {
1305 attrs: variant_attrs,
1308 span: vlo.to(self.prev_span),
1309 is_placeholder: false,
1315 /// Parses `struct Foo { ... }`.
1316 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1317 let class_name = self.parse_ident()?;
1319 let mut generics = self.parse_generics()?;
1321 // There is a special case worth noting here, as reported in issue #17904.
1322 // If we are parsing a tuple struct it is the case that the where clause
1323 // should follow the field list. Like so:
1325 // struct Foo<T>(T) where T: Copy;
1327 // If we are parsing a normal record-style struct it is the case
1328 // that the where clause comes before the body, and after the generics.
1329 // So if we look ahead and see a brace or a where-clause we begin
1330 // parsing a record style struct.
1332 // Otherwise if we look ahead and see a paren we parse a tuple-style
1335 let vdata = if self.token.is_keyword(kw::Where) {
1336 generics.where_clause = self.parse_where_clause()?;
1337 if self.eat(&token::Semi) {
1338 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1339 VariantData::Unit(DUMMY_NODE_ID)
1341 // If we see: `struct Foo<T> where T: Copy { ... }`
1342 let (fields, recovered) = self.parse_record_struct_body()?;
1343 VariantData::Struct(fields, recovered)
1345 // No `where` so: `struct Foo<T>;`
1346 } else if self.eat(&token::Semi) {
1347 VariantData::Unit(DUMMY_NODE_ID)
1348 // Record-style struct definition
1349 } else if self.token == token::OpenDelim(token::Brace) {
1350 let (fields, recovered) = self.parse_record_struct_body()?;
1351 VariantData::Struct(fields, recovered)
1352 // Tuple-style struct definition with optional where-clause.
1353 } else if self.token == token::OpenDelim(token::Paren) {
1354 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1355 generics.where_clause = self.parse_where_clause()?;
1356 self.expect_semi()?;
1359 let token_str = super::token_descr(&self.token);
1361 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1364 let mut err = self.struct_span_err(self.token.span, msg);
1365 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1369 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1372 /// Parses `union Foo { ... }`.
1373 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1374 let class_name = self.parse_ident()?;
1376 let mut generics = self.parse_generics()?;
1378 let vdata = if self.token.is_keyword(kw::Where) {
1379 generics.where_clause = self.parse_where_clause()?;
1380 let (fields, recovered) = self.parse_record_struct_body()?;
1381 VariantData::Struct(fields, recovered)
1382 } else if self.token == token::OpenDelim(token::Brace) {
1383 let (fields, recovered) = self.parse_record_struct_body()?;
1384 VariantData::Struct(fields, recovered)
1386 let token_str = super::token_descr(&self.token);
1387 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1388 let mut err = self.struct_span_err(self.token.span, msg);
1389 err.span_label(self.token.span, "expected `where` or `{` after union name");
1393 Ok((class_name, ItemKind::Union(vdata, generics), None))
1396 pub(super) fn is_union_item(&self) -> bool {
1397 self.token.is_keyword(kw::Union)
1398 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1401 fn parse_record_struct_body(
1403 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1404 let mut fields = Vec::new();
1405 let mut recovered = false;
1406 if self.eat(&token::OpenDelim(token::Brace)) {
1407 while self.token != token::CloseDelim(token::Brace) {
1408 let field = self.parse_struct_decl_field().map_err(|e| {
1409 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1414 Ok(field) => fields.push(field),
1421 self.eat(&token::CloseDelim(token::Brace));
1423 let token_str = super::token_descr(&self.token);
1424 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1425 let mut err = self.struct_span_err(self.token.span, msg);
1426 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1430 Ok((fields, recovered))
1433 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1434 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1435 // Unit like structs are handled in parse_item_struct function
1436 self.parse_paren_comma_seq(|p| {
1437 let attrs = p.parse_outer_attributes()?;
1438 let lo = p.token.span;
1439 let vis = p.parse_visibility(FollowedByType::Yes)?;
1440 let ty = p.parse_ty()?;
1442 span: lo.to(ty.span),
1448 is_placeholder: false,
1454 /// Parses an element of a struct declaration.
1455 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1456 let attrs = self.parse_outer_attributes()?;
1457 let lo = self.token.span;
1458 let vis = self.parse_visibility(FollowedByType::No)?;
1459 self.parse_single_struct_field(lo, vis, attrs)
1462 /// Parses a structure field declaration.
1463 fn parse_single_struct_field(
1467 attrs: Vec<Attribute>,
1468 ) -> PResult<'a, StructField> {
1469 let mut seen_comma: bool = false;
1470 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1471 if self.token == token::Comma {
1474 match self.token.kind {
1478 token::CloseDelim(token::Brace) => {}
1479 token::DocComment(_) => {
1480 let previous_span = self.prev_span;
1481 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1482 self.bump(); // consume the doc comment
1483 let comma_after_doc_seen = self.eat(&token::Comma);
1484 // `seen_comma` is always false, because we are inside doc block
1485 // condition is here to make code more readable
1486 if seen_comma == false && comma_after_doc_seen == true {
1489 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1492 if seen_comma == false {
1493 let sp = self.sess.source_map().next_point(previous_span);
1494 err.span_suggestion(
1496 "missing comma here",
1498 Applicability::MachineApplicable,
1505 let sp = self.prev_span.shrink_to_hi();
1506 let mut err = self.struct_span_err(
1508 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1510 if self.token.is_ident() {
1511 // This is likely another field; emit the diagnostic and keep going
1512 err.span_suggestion(
1514 "try adding a comma",
1516 Applicability::MachineApplicable,
1527 /// Parses a structure field.
1528 fn parse_name_and_ty(
1532 attrs: Vec<Attribute>,
1533 ) -> PResult<'a, StructField> {
1534 let name = self.parse_ident()?;
1535 self.expect(&token::Colon)?;
1536 let ty = self.parse_ty()?;
1538 span: lo.to(self.prev_span),
1544 is_placeholder: false,
1548 pub(super) fn eat_macro_def(
1550 attrs: &[Attribute],
1553 ) -> PResult<'a, Option<P<Item>>> {
1554 let (ident, def) = if self.eat_keyword(kw::Macro) {
1555 let ident = self.parse_ident()?;
1556 let body = if self.check(&token::OpenDelim(token::Brace)) {
1557 self.parse_mac_args()?
1558 } else if self.check(&token::OpenDelim(token::Paren)) {
1559 let params = self.parse_token_tree();
1560 let pspan = params.span();
1561 let body = if self.check(&token::OpenDelim(token::Brace)) {
1562 self.parse_token_tree()
1564 return self.unexpected();
1566 let bspan = body.span();
1567 let tokens = TokenStream::new(vec![
1569 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1572 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1573 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1575 return self.unexpected();
1578 (ident, ast::MacroDef { body, legacy: false })
1579 } else if self.check_keyword(sym::macro_rules)
1580 && self.look_ahead(1, |t| *t == token::Not)
1581 && self.look_ahead(2, |t| t.is_ident())
1583 let prev_span = self.prev_span;
1584 self.complain_if_pub_macro(&vis.node, prev_span);
1588 let ident = self.parse_ident()?;
1589 let body = self.parse_mac_args()?;
1590 if body.need_semicolon() && !self.eat(&token::Semi) {
1591 self.report_invalid_macro_expansion_item();
1594 (ident, ast::MacroDef { body, legacy: true })
1599 let span = lo.to(self.prev_span);
1602 self.sess.gated_spans.gate(sym::decl_macro, span);
1605 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1608 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1610 VisibilityKind::Inherited => {}
1612 let mut err = if self.token.is_keyword(sym::macro_rules) {
1614 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1615 err.span_suggestion(
1617 "try exporting the macro",
1618 "#[macro_export]".to_owned(),
1619 Applicability::MaybeIncorrect, // speculative
1624 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1625 err.help("try adjusting the macro to put `pub` inside the invocation");
1633 fn report_invalid_macro_expansion_item(&self) {
1634 let has_close_delim = self
1637 .span_to_snippet(self.prev_span)
1638 .map(|s| s.ends_with(")") || s.ends_with("]"))
1641 let mut err = self.struct_span_err(
1643 "macros that expand to items must be delimited with braces or followed by a semicolon",
1646 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1647 if has_close_delim {
1648 err.multipart_suggestion(
1649 "change the delimiters to curly braces",
1651 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1652 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1654 Applicability::MaybeIncorrect,
1657 err.span_suggestion(
1659 "change the delimiters to curly braces",
1660 " { /* items */ }".to_string(),
1661 Applicability::HasPlaceholders,
1665 err.span_suggestion(
1666 self.prev_span.shrink_to_hi(),
1669 Applicability::MaybeIncorrect,
1674 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1675 /// it is, we try to parse the item and report error about nested types.
1676 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1677 if (self.token.is_keyword(kw::Enum)
1678 || self.token.is_keyword(kw::Struct)
1679 || self.token.is_keyword(kw::Union))
1680 && self.look_ahead(1, |t| t.is_ident())
1682 let kw_token = self.token.clone();
1683 let kw_str = pprust::token_to_string(&kw_token);
1684 let item = self.parse_item()?;
1686 self.struct_span_err(
1688 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1692 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1694 Applicability::MaybeIncorrect,
1697 // We successfully parsed the item but we must inform the caller about nested problem.
1709 attrs: Vec<Attribute>,
1711 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1715 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1716 pub(super) struct ParamCfg {
1717 /// `is_name_required` decides if, per-parameter,
1718 /// the parameter must have a pattern or just a type.
1719 pub is_name_required: fn(&token::Token) -> bool,
1722 /// Parsing of functions and methods.
1723 impl<'a> Parser<'a> {
1724 /// Parses an item-position function declaration.
1729 attrs: Vec<Attribute>,
1731 ) -> PResult<'a, Option<P<Item>>> {
1732 let cfg = ParamCfg { is_name_required: |_| true };
1733 let (ident, decl, generics) = self.parse_fn_sig(&cfg)?;
1734 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1735 let kind = ItemKind::Fn(FnSig { decl, header }, generics, body);
1736 self.mk_item_with_info(attrs, lo, vis, (ident, kind, Some(inner_attrs)))
1739 /// Parses a function declaration from a foreign module.
1740 fn parse_item_foreign_fn(
1742 vis: ast::Visibility,
1744 attrs: Vec<Attribute>,
1746 ) -> PResult<'a, P<ForeignItem>> {
1747 let cfg = ParamCfg { is_name_required: |_| true };
1748 self.expect_keyword(kw::Fn)?;
1749 let (ident, decl, generics) = self.parse_fn_sig(&cfg)?;
1750 let span = lo.to(self.token.span);
1751 self.parse_semi_or_incorrect_foreign_fn_body(&ident, extern_sp)?;
1752 let kind = ForeignItemKind::Fn(decl, generics);
1753 Ok(P(ast::ForeignItem { ident, attrs, kind, id: DUMMY_NODE_ID, span, vis, tokens: None }))
1759 attrs: &mut Vec<Attribute>,
1760 is_name_required: fn(&token::Token) -> bool,
1761 ) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
1762 let header = self.parse_fn_front_matter()?;
1763 let (ident, decl, generics) = self.parse_fn_sig(&ParamCfg { is_name_required })?;
1764 let sig = FnSig { header, decl };
1765 let body = self.parse_assoc_fn_body(at_end, attrs)?;
1766 Ok((ident, AssocItemKind::Fn(sig, body), generics))
1769 /// Parse the "body" of a method in an associated item definition.
1770 /// This can either be `;` when there's no body,
1771 /// or e.g. a block when the method is a provided one.
1772 fn parse_assoc_fn_body(
1775 attrs: &mut Vec<Attribute>,
1776 ) -> PResult<'a, Option<P<Block>>> {
1777 Ok(match self.token.kind {
1779 debug!("parse_assoc_fn_body(): parsing required method");
1784 token::OpenDelim(token::Brace) => {
1785 debug!("parse_assoc_fn_body(): parsing provided method");
1787 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1788 attrs.extend(inner_attrs.iter().cloned());
1791 token::Interpolated(ref nt) => match **nt {
1792 token::NtBlock(..) => {
1794 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1795 attrs.extend(inner_attrs.iter().cloned());
1798 _ => return self.expected_semi_or_open_brace(),
1800 _ => return self.expected_semi_or_open_brace(),
1804 /// Parses all the "front matter" for a `fn` declaration, up to
1805 /// and including the `fn` keyword:
1809 /// - `const unsafe fn`
1812 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1813 let is_const_fn = self.eat_keyword(kw::Const);
1814 let const_span = self.prev_span;
1815 let asyncness = self.parse_asyncness();
1816 if let IsAsync::Async { .. } = asyncness {
1817 self.ban_async_in_2015(self.prev_span);
1819 let asyncness = respan(self.prev_span, asyncness);
1820 let unsafety = self.parse_unsafety();
1821 let (constness, unsafety, ext) = if is_const_fn {
1822 (respan(const_span, Constness::Const), unsafety, Extern::None)
1824 let ext = self.parse_extern()?;
1825 (respan(self.prev_span, Constness::NotConst), unsafety, ext)
1827 if !self.eat_keyword(kw::Fn) {
1828 // It is possible for `expect_one_of` to recover given the contents of
1829 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1830 // account for this.
1831 if !self.expect_one_of(&[], &[])? {
1835 Ok(FnHeader { constness, unsafety, asyncness, ext })
1838 /// Parse the "signature", including the identifier, parameters, and generics of a function.
1839 fn parse_fn_sig(&mut self, cfg: &ParamCfg) -> PResult<'a, (Ident, P<FnDecl>, Generics)> {
1840 let ident = self.parse_ident()?;
1841 let mut generics = self.parse_generics()?;
1842 let decl = self.parse_fn_decl(cfg, true)?;
1843 generics.where_clause = self.parse_where_clause()?;
1844 Ok((ident, decl, generics))
1847 /// Parses the parameter list and result type of a function declaration.
1848 pub(super) fn parse_fn_decl(
1851 ret_allow_plus: bool,
1852 ) -> PResult<'a, P<FnDecl>> {
1854 inputs: self.parse_fn_params(cfg)?,
1855 output: self.parse_ret_ty(ret_allow_plus, true)?,
1859 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1860 fn parse_fn_params(&mut self, cfg: &ParamCfg) -> PResult<'a, Vec<Param>> {
1861 let mut first_param = true;
1862 // Parse the arguments, starting out with `self` being allowed...
1863 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1864 let param = p.parse_param_general(&cfg, first_param).or_else(|mut e| {
1866 let lo = p.prev_span;
1867 // Skip every token until next possible arg or end.
1868 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1869 // Create a placeholder argument for proper arg count (issue #34264).
1870 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1872 // ...now that we've parsed the first argument, `self` is no longer allowed.
1873 first_param = false;
1876 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1877 self.deduplicate_recovered_params_names(&mut params);
1881 /// Parses a single function parameter.
1883 /// - `self` is syntactically allowed when `first_param` holds.
1884 fn parse_param_general(&mut self, cfg: &ParamCfg, first_param: bool) -> PResult<'a, Param> {
1885 let lo = self.token.span;
1886 let attrs = self.parse_outer_attributes()?;
1888 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1889 if let Some(mut param) = self.parse_self_param()? {
1890 param.attrs = attrs.into();
1891 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1894 let is_name_required = match self.token.kind {
1895 token::DotDotDot => false,
1896 _ => (cfg.is_name_required)(&self.token),
1898 let (pat, ty) = if is_name_required || self.is_named_param() {
1899 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1901 let pat = self.parse_fn_param_pat()?;
1902 if let Err(mut err) = self.expect(&token::Colon) {
1903 return if let Some(ident) =
1904 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1907 Ok(dummy_arg(ident))
1913 self.eat_incorrect_doc_comment_for_param_type();
1914 (pat, self.parse_ty_for_param()?)
1916 debug!("parse_param_general ident_to_pat");
1917 let parser_snapshot_before_ty = self.clone();
1918 self.eat_incorrect_doc_comment_for_param_type();
1919 let mut ty = self.parse_ty_for_param();
1921 && self.token != token::Comma
1922 && self.token != token::CloseDelim(token::Paren)
1924 // This wasn't actually a type, but a pattern looking like a type,
1925 // so we are going to rollback and re-parse for recovery.
1926 ty = self.unexpected();
1930 let ident = Ident::new(kw::Invalid, self.prev_span);
1931 let bm = BindingMode::ByValue(Mutability::Not);
1932 let pat = self.mk_pat_ident(ty.span, bm, ident);
1935 // If this is a C-variadic argument and we hit an error, return the error.
1936 Err(err) if self.token == token::DotDotDot => return Err(err),
1937 // Recover from attempting to parse the argument as a type without pattern.
1940 mem::replace(self, parser_snapshot_before_ty);
1941 self.recover_arg_parse()?
1946 let span = lo.to(self.token.span);
1949 attrs: attrs.into(),
1950 id: ast::DUMMY_NODE_ID,
1951 is_placeholder: false,
1958 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1959 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1960 // Extract an identifier *after* having confirmed that the token is one.
1961 let expect_self_ident = |this: &mut Self| {
1962 match this.token.kind {
1963 // Preserve hygienic context.
1964 token::Ident(name, _) => {
1965 let span = this.token.span;
1967 Ident::new(name, span)
1969 _ => unreachable!(),
1972 // Is `self` `n` tokens ahead?
1973 let is_isolated_self = |this: &Self, n| {
1974 this.is_keyword_ahead(n, &[kw::SelfLower])
1975 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1977 // Is `mut self` `n` tokens ahead?
1978 let is_isolated_mut_self =
1979 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1980 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1981 let parse_self_possibly_typed = |this: &mut Self, m| {
1982 let eself_ident = expect_self_ident(this);
1983 let eself_hi = this.prev_span;
1984 let eself = if this.eat(&token::Colon) {
1985 SelfKind::Explicit(this.parse_ty()?, m)
1989 Ok((eself, eself_ident, eself_hi))
1991 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1992 let recover_self_ptr = |this: &mut Self| {
1993 let msg = "cannot pass `self` by raw pointer";
1994 let span = this.token.span;
1995 this.struct_span_err(span, msg).span_label(span, msg).emit();
1997 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
2000 // Parse optional `self` parameter of a method.
2001 // Only a limited set of initial token sequences is considered `self` parameters; anything
2002 // else is parsed as a normal function parameter list, so some lookahead is required.
2003 let eself_lo = self.token.span;
2004 let (eself, eself_ident, eself_hi) = match self.token.kind {
2005 token::BinOp(token::And) => {
2006 let eself = if is_isolated_self(self, 1) {
2009 SelfKind::Region(None, Mutability::Not)
2010 } else if is_isolated_mut_self(self, 1) {
2014 SelfKind::Region(None, Mutability::Mut)
2015 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2018 let lt = self.expect_lifetime();
2019 SelfKind::Region(Some(lt), Mutability::Not)
2020 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2023 let lt = self.expect_lifetime();
2025 SelfKind::Region(Some(lt), Mutability::Mut)
2030 (eself, expect_self_ident(self), self.prev_span)
2033 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2035 recover_self_ptr(self)?
2037 // `*mut self` and `*const self`
2038 token::BinOp(token::Star)
2039 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2043 recover_self_ptr(self)?
2045 // `self` and `self: TYPE`
2046 token::Ident(..) if is_isolated_self(self, 0) => {
2047 parse_self_possibly_typed(self, Mutability::Not)?
2049 // `mut self` and `mut self: TYPE`
2050 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2052 parse_self_possibly_typed(self, Mutability::Mut)?
2054 _ => return Ok(None),
2057 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2058 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2061 fn is_named_param(&self) -> bool {
2062 let offset = match self.token.kind {
2063 token::Interpolated(ref nt) => match **nt {
2064 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2067 token::BinOp(token::And) | token::AndAnd => 1,
2068 _ if self.token.is_keyword(kw::Mut) => 1,
2072 self.look_ahead(offset, |t| t.is_ident())
2073 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2076 fn recover_first_param(&mut self) -> &'static str {
2078 .parse_outer_attributes()
2079 .and_then(|_| self.parse_self_param())
2080 .map_err(|mut e| e.cancel())
2082 Ok(Some(_)) => "method",