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, Span};
10 use rustc_span::symbol::{kw, sym, Symbol};
11 use syntax::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
12 use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind};
13 use syntax::ast::{Async, Const, Defaultness, IsAuto, PathSegment, Unsafe};
14 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
15 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
16 use syntax::ast::{FnHeader, ForeignItem, Mutability, Visibility, VisibilityKind};
19 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
24 pub(super) type ItemInfo = (Ident, ItemKind);
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 item = self.parse_item_common(attrs, macros_allowed, attributes_allowed)?;
85 if let Some(ref item) = item {
86 self.error_on_illegal_default(item.defaultness);
93 mut attrs: Vec<Attribute>,
95 attributes_allowed: bool,
96 ) -> PResult<'a, Option<Item>> {
97 let lo = self.token.span;
98 let vis = self.parse_visibility(FollowedByType::No)?;
99 let mut def = self.parse_defaultness();
100 let kind = self.parse_item_kind(&mut attrs, macros_allowed, lo, &vis, &mut def)?;
101 if let Some((ident, kind)) = kind {
102 return Ok(Some(self.mk_item(lo, ident, kind, vis, def, attrs)));
105 // At this point, we have failed to parse an item.
106 self.error_on_unmatched_vis(&vis);
107 self.error_on_unmatched_defaultness(def);
108 if !attributes_allowed {
109 self.recover_attrs_no_item(&attrs)?;
114 /// Error in-case a non-inherited visibility was parsed but no item followed.
115 fn error_on_unmatched_vis(&self, vis: &Visibility) {
116 if let VisibilityKind::Inherited = vis.node {
119 let vs = pprust::vis_to_string(&vis);
120 let vs = vs.trim_end();
121 self.struct_span_err(vis.span, &format!("unmatched visibility `{}`", vs))
122 .span_label(vis.span, "the unmatched visibility")
123 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
127 /// Error in-case a `default` was parsed but no item followed.
128 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
129 if let Defaultness::Default(span) = def {
130 self.struct_span_err(span, "unmatched `default`")
131 .span_label(span, "the unmatched `default`")
136 /// Error in-case `default` was parsed in an in-appropriate context.
137 fn error_on_illegal_default(&self, def: Defaultness) {
138 if let Defaultness::Default(span) = def {
139 self.struct_span_err(span, "item cannot be `default`")
140 .span_label(span, "`default` because of this")
141 .note("only associated `fn`, `const`, and `type` items can be `default`")
146 /// Parses one of the items allowed by the flags.
149 attrs: &mut Vec<Attribute>,
150 macros_allowed: bool,
153 def: &mut Defaultness,
154 ) -> PResult<'a, Option<ItemInfo>> {
155 let info = if self.eat_keyword(kw::Use) {
157 let tree = self.parse_use_tree()?;
159 (Ident::invalid(), ItemKind::Use(P(tree)))
160 } else if self.check_fn_front_matter() {
162 let (ident, sig, generics, body) = self.parse_fn(&mut false, attrs, |_| true)?;
163 (ident, ItemKind::Fn(sig, generics, body))
164 } else if self.eat_keyword(kw::Extern) {
165 if self.eat_keyword(kw::Crate) {
167 self.parse_item_extern_crate()?
170 self.parse_item_foreign_mod(attrs)?
172 } else if self.is_static_global() {
174 self.bump(); // `static`
175 let m = self.parse_mutability();
176 self.parse_item_const(Some(m))?
177 } else if let Const::Yes(const_span) = self.parse_constness() {
179 self.recover_const_mut(const_span);
180 self.parse_item_const(None)?
181 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
183 self.parse_item_trait(attrs, lo)?
184 } else if self.check_keyword(kw::Impl)
185 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
188 self.parse_item_impl(attrs, mem::replace(def, Defaultness::Final))?
189 } else if self.eat_keyword(kw::Mod) {
191 self.parse_item_mod(attrs)?
192 } else if self.eat_keyword(kw::Type) {
194 self.parse_type_alias()?
195 } else if self.eat_keyword(kw::Enum) {
197 self.parse_item_enum()?
198 } else if self.eat_keyword(kw::Struct) {
200 self.parse_item_struct()?
201 } else if self.is_kw_followed_by_ident(kw::Union) {
203 self.bump(); // `union`
204 self.parse_item_union()?
205 } else if self.eat_keyword(kw::Macro) {
207 self.parse_item_decl_macro(lo)?
208 } else if self.is_macro_rules_item() {
210 self.parse_item_macro_rules(vis)?
211 } else if vis.node.is_pub() && self.isnt_macro_invocation() {
212 self.recover_missing_kw_before_item()?;
214 } else if macros_allowed && self.token.is_path_start() {
215 // MACRO INVOCATION ITEM
216 (Ident::invalid(), ItemKind::Mac(self.parse_item_macro(vis)?))
223 /// When parsing a statement, would the start of a path be an item?
224 pub(super) fn is_path_start_item(&mut self) -> bool {
225 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
226 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
227 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
228 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
229 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
232 /// Are we sure this could not possibly be a macro invocation?
233 fn isnt_macro_invocation(&mut self) -> bool {
234 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
237 /// Recover on encountering a struct or method definition where the user
238 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
239 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
240 // Space between `pub` keyword and the identifier
243 // ^^^ `sp` points here
244 let sp = self.prev_span.between(self.token.span);
245 let full_sp = self.prev_span.to(self.token.span);
246 let ident_sp = self.token.span;
247 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
248 // possible public struct definition where `struct` was forgotten
249 let ident = self.parse_ident().unwrap();
250 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
251 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
252 err.span_suggestion_short(
256 Applicability::MaybeIncorrect, // speculative
259 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
260 let ident = self.parse_ident().unwrap();
262 let kw_name = self.recover_first_param();
263 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
264 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
265 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
267 ("fn", kw_name, false)
268 } else if self.check(&token::OpenDelim(token::Brace)) {
270 ("fn", kw_name, false)
271 } else if self.check(&token::Colon) {
275 ("fn` or `struct", "function or struct", true)
278 let msg = format!("missing `{}` for {} definition", kw, kw_name);
279 let mut err = self.struct_span_err(sp, &msg);
281 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
283 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
284 err.span_suggestion_short(
288 Applicability::MachineApplicable,
291 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
294 "if you meant to call a macro, try",
295 format!("{}!", snippet),
296 // this is the `ambiguous` conditional branch
297 Applicability::MaybeIncorrect,
301 "if you meant to call a macro, remove the `pub` \
302 and add a trailing `!` after the identifier",
307 } else if self.look_ahead(1, |t| *t == token::Lt) {
308 let ident = self.parse_ident().unwrap();
309 self.eat_to_tokens(&[&token::Gt]);
311 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
312 ("fn", self.recover_first_param(), false)
313 } else if self.check(&token::OpenDelim(token::Brace)) {
314 ("struct", "struct", false)
316 ("fn` or `struct", "function or struct", true)
318 let msg = format!("missing `{}` for {} definition", kw, kw_name);
319 let mut err = self.struct_span_err(sp, &msg);
321 err.span_suggestion_short(
323 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
325 Applicability::MachineApplicable,
334 /// Parses an item macro, e.g., `item!();`.
335 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, Mac> {
336 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
337 self.expect(&token::Not)?; // `!`
338 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
339 self.eat_semi_for_macro_if_needed(&args);
340 self.complain_if_pub_macro(vis, false);
341 Ok(Mac { path, args, prior_type_ascription: self.last_type_ascription })
344 /// Recover if we parsed attributes and expected an item but there was none.
345 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
346 let (start, end) = match attrs {
349 [x0, .., xn] => (x0, xn),
351 let msg = if end.is_doc_comment() {
352 "expected item after doc comment"
354 "expected item after attributes"
356 let mut err = self.struct_span_err(end.span, msg);
357 if end.is_doc_comment() {
358 err.span_label(end.span, "this doc comment doesn't document anything");
360 if let [.., penultimate, _] = attrs {
361 err.span_label(start.span.to(penultimate.span), "other attributes here");
366 fn is_async_fn(&self) -> bool {
367 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
370 /// Given this code `path(`, it seems like this is not
371 /// setting the visibility of a macro invocation,
372 /// but rather a mistyped method declaration.
373 /// Create a diagnostic pointing out that `fn` is missing.
376 /// x | pub path(&self) {
377 /// | ^ missing `fn`, `type`, `const`, or `static`
379 fn missing_nested_item_kind_err(&self, prev_span: Span) -> DiagnosticBuilder<'a> {
380 let sp = prev_span.between(self.token.span);
381 let expected_kinds = "missing `fn`, `type`, `const`, or `static`";
382 let mut err = self.struct_span_err(sp, &format!("{} for item declaration", expected_kinds));
383 err.span_label(sp, expected_kinds);
387 /// Parses an implementation item.
390 /// impl<'a, T> TYPE { /* impl items */ }
391 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
392 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
393 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
396 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
398 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
399 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
403 attrs: &mut Vec<Attribute>,
404 defaultness: Defaultness,
405 ) -> PResult<'a, ItemInfo> {
406 let unsafety = self.parse_unsafety();
407 self.expect_keyword(kw::Impl)?;
409 // First, parse generic parameters if necessary.
410 let mut generics = if self.choose_generics_over_qpath() {
411 self.parse_generics()?
413 let mut generics = Generics::default();
415 // /\ this is where `generics.span` should point when there are no type params.
416 generics.span = self.prev_span.shrink_to_hi();
420 let constness = self.parse_constness();
421 if let Const::Yes(span) = constness {
422 self.sess.gated_spans.gate(sym::const_trait_impl, span);
425 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
426 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
428 ast::ImplPolarity::Negative
430 ast::ImplPolarity::Positive
433 // Parse both types and traits as a type, then reinterpret if necessary.
434 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
435 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
437 let span = self.prev_span.between(self.token.span);
438 self.struct_span_err(span, "missing trait in a trait impl").emit();
439 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
444 // If `for` is missing we try to recover.
445 let has_for = self.eat_keyword(kw::For);
446 let missing_for_span = self.prev_span.between(self.token.span);
448 let ty_second = if self.token == token::DotDot {
449 // We need to report this error after `cfg` expansion for compatibility reasons
450 self.bump(); // `..`, do not add it to expected tokens
451 Some(self.mk_ty(self.prev_span, TyKind::Err))
452 } else if has_for || self.token.can_begin_type() {
453 Some(self.parse_ty()?)
458 generics.where_clause = self.parse_where_clause()?;
461 self.parse_item_list(attrs, |p, at_end| p.parse_impl_item(at_end).map(Some).map(Some))?;
463 let item_kind = match ty_second {
465 // impl Trait for Type
467 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
468 .span_suggestion_short(
472 Applicability::MachineApplicable,
477 let ty_first = ty_first.into_inner();
478 let path = match ty_first.kind {
479 // This notably includes paths passed through `ty` macro fragments (#46438).
480 TyKind::Path(None, path) => path,
482 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
483 err_path(ty_first.span)
486 let trait_ref = TraitRef { path, ref_id: ty_first.id };
494 of_trait: Some(trait_ref),
514 Ok((Ident::invalid(), item_kind))
517 fn parse_item_list<T>(
519 attrs: &mut Vec<Attribute>,
520 mut parse_item: impl FnMut(&mut Parser<'a>, &mut bool) -> PResult<'a, Option<Option<T>>>,
521 ) -> PResult<'a, Vec<T>> {
522 let open_brace_span = self.token.span;
523 self.expect(&token::OpenDelim(token::Brace))?;
524 attrs.append(&mut self.parse_inner_attributes()?);
526 let mut items = Vec::new();
527 while !self.eat(&token::CloseDelim(token::Brace)) {
528 if self.recover_doc_comment_before_brace() {
531 let mut at_end = false;
532 match parse_item(self, &mut at_end) {
534 // We have to bail or we'll potentially never make progress.
535 let non_item_span = self.token.span;
536 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
537 self.struct_span_err(non_item_span, "non-item in item list")
538 .span_label(open_brace_span, "item list starts here")
539 .span_label(non_item_span, "non-item starts here")
540 .span_label(self.prev_span, "item list ends here")
544 Ok(Some(item)) => items.extend(item),
548 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
557 /// Recover on a doc comment before `}`.
558 fn recover_doc_comment_before_brace(&mut self) -> bool {
559 if let token::DocComment(_) = self.token.kind {
560 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
565 "found a documentation comment that doesn't document anything",
567 .span_label(self.token.span, "this doc comment doesn't document anything")
569 "doc comments must come before what they document, maybe a \
570 comment was intended with `//`?",
580 /// Parses defaultness (i.e., `default` or nothing).
581 fn parse_defaultness(&mut self) -> Defaultness {
582 // We are interested in `default` followed by another identifier.
583 // However, we must avoid keywords that occur as binary operators.
584 // Currently, the only applicable keyword is `as` (`default as Ty`).
585 if self.check_keyword(kw::Default)
586 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
588 self.bump(); // `default`
589 Defaultness::Default(self.prev_span)
595 /// Is this an `(unsafe auto? | auto) trait` item?
596 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
598 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
600 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
603 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
604 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
605 let unsafety = self.parse_unsafety();
606 // Parse optional `auto` prefix.
607 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
609 self.expect_keyword(kw::Trait)?;
610 let ident = self.parse_ident()?;
611 let mut tps = self.parse_generics()?;
613 // Parse optional colon and supertrait bounds.
614 let had_colon = self.eat(&token::Colon);
615 let span_at_colon = self.prev_span;
617 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
619 let span_before_eq = self.prev_span;
620 if self.eat(&token::Eq) {
621 // It's a trait alias.
623 let span = span_at_colon.to(span_before_eq);
624 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
627 let bounds = self.parse_generic_bounds(None)?;
628 tps.where_clause = self.parse_where_clause()?;
631 let whole_span = lo.to(self.prev_span);
632 if is_auto == IsAuto::Yes {
633 let msg = "trait aliases cannot be `auto`";
634 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
636 if let Unsafe::Yes(_) = unsafety {
637 let msg = "trait aliases cannot be `unsafe`";
638 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
641 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
643 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
645 // It's a normal trait.
646 tps.where_clause = self.parse_where_clause()?;
647 let items = self.parse_item_list(attrs, |p, at_end| {
648 p.parse_trait_item(at_end).map(Some).map(Some)
650 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
654 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
655 maybe_whole!(self, NtImplItem, |x| x);
656 self.parse_assoc_item(at_end, |_| true)
659 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
660 maybe_whole!(self, NtTraitItem, |x| x);
661 // This is somewhat dubious; We don't want to allow
662 // param names to be left off if there is a definition...
664 // We don't allow param names to be left off in edition 2018.
665 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
668 /// Parses associated items.
673 ) -> PResult<'a, P<AssocItem>> {
674 let attrs = self.parse_outer_attributes()?;
675 let mut unclosed_delims = vec![];
676 let (mut item, tokens) = self.collect_tokens(|this| {
677 let item = this.parse_assoc_item_(at_end, attrs, req_name);
678 unclosed_delims.append(&mut this.unclosed_delims);
681 self.unclosed_delims.append(&mut unclosed_delims);
682 // See `parse_item` for why this clause is here.
683 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
684 item.tokens = Some(tokens);
686 self.error_on_assoc_static(&item);
690 fn error_on_assoc_static(&self, item: &AssocItem) {
691 if let AssocItemKind::Static(..) = item.kind {
692 self.struct_span_err(item.span, "associated `static` items are not allowed").emit();
696 fn parse_assoc_item_(
699 mut attrs: Vec<Attribute>,
701 ) -> PResult<'a, AssocItem> {
702 let lo = self.token.span;
703 let vis = self.parse_visibility(FollowedByType::No)?;
704 let defaultness = self.parse_defaultness();
705 let (ident, kind) = self.parse_assoc_item_kind(at_end, &mut attrs, req_name, &vis)?;
706 let span = lo.to(self.prev_span);
707 let id = DUMMY_NODE_ID;
708 Ok(AssocItem { id, span, ident, attrs, vis, defaultness, kind, tokens: None })
711 fn parse_assoc_item_kind(
714 attrs: &mut Vec<Attribute>,
717 ) -> PResult<'a, (Ident, AssocItemKind)> {
718 if self.eat_keyword(kw::Type) {
719 match self.parse_type_alias()? {
720 (ident, ItemKind::TyAlias(a, b, c)) => Ok((ident, AssocItemKind::TyAlias(a, b, c))),
723 } else if self.check_fn_front_matter() {
724 let (ident, sig, generics, body) = self.parse_fn(at_end, attrs, req_name)?;
725 Ok((ident, AssocItemKind::Fn(sig, generics, body)))
726 } else if self.is_static_global() {
727 self.bump(); // `static`
728 let mutbl = self.parse_mutability();
729 let (ident, ty, expr) = self.parse_item_const_common(Some(mutbl))?;
730 Ok((ident, AssocItemKind::Static(ty, mutbl, expr)))
731 } else if self.eat_keyword(kw::Const) {
732 let (ident, ty, expr) = self.parse_item_const_common(None)?;
733 Ok((ident, AssocItemKind::Const(ty, expr)))
734 } else if self.isnt_macro_invocation() {
735 Err(self.missing_nested_item_kind_err(self.prev_span))
736 } else if self.token.is_path_start() {
737 let mac = self.parse_item_macro(&vis)?;
739 Ok((Ident::invalid(), AssocItemKind::Macro(mac)))
741 self.recover_attrs_no_item(attrs)?;
746 /// Parses a `type` alias with the following grammar:
748 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
750 /// The `"type"` has already been eaten.
751 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, ItemKind)> {
752 let ident = self.parse_ident()?;
753 let mut generics = self.parse_generics()?;
755 // Parse optional colon and param bounds.
757 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
758 generics.where_clause = self.parse_where_clause()?;
760 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
763 Ok((ident, ItemKind::TyAlias(generics, bounds, default)))
766 /// Parses a `UseTree`.
769 /// USE_TREE = [`::`] `*` |
770 /// [`::`] `{` USE_TREE_LIST `}` |
772 /// PATH `::` `{` USE_TREE_LIST `}` |
773 /// PATH [`as` IDENT]
775 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
776 let lo = self.token.span;
778 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
779 let kind = if self.check(&token::OpenDelim(token::Brace))
780 || self.check(&token::BinOp(token::Star))
781 || self.is_import_coupler()
783 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
784 let mod_sep_ctxt = self.token.span.ctxt();
785 if self.eat(&token::ModSep) {
788 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
791 self.parse_use_tree_glob_or_nested()?
793 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
794 prefix = self.parse_path(PathStyle::Mod)?;
796 if self.eat(&token::ModSep) {
797 self.parse_use_tree_glob_or_nested()?
799 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
803 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
806 /// Parses `*` or `{...}`.
807 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
808 Ok(if self.eat(&token::BinOp(token::Star)) {
811 UseTreeKind::Nested(self.parse_use_tree_list()?)
815 /// Parses a `UseTreeKind::Nested(list)`.
818 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
820 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
821 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
825 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
826 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
829 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
830 match self.token.kind {
831 token::Ident(name @ kw::Underscore, false) => {
832 let span = self.token.span;
834 Ok(Ident::new(name, span))
836 _ => self.parse_ident(),
840 /// Parses `extern crate` links.
845 /// extern crate foo;
846 /// extern crate bar as foo;
848 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
849 // Accept `extern crate name-like-this` for better diagnostics
850 let orig_name = self.parse_crate_name_with_dashes()?;
851 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
852 (rename, Some(orig_name.name))
857 Ok((item_name, ItemKind::ExternCrate(orig_name)))
860 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
861 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
862 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
864 let mut ident = if self.token.is_keyword(kw::SelfLower) {
865 self.parse_path_segment_ident()
869 let mut idents = vec![];
870 let mut replacement = vec![];
871 let mut fixed_crate_name = false;
872 // Accept `extern crate name-like-this` for better diagnostics.
873 let dash = token::BinOp(token::BinOpToken::Minus);
874 if self.token == dash {
875 // Do not include `-` as part of the expected tokens list.
876 while self.eat(&dash) {
877 fixed_crate_name = true;
878 replacement.push((self.prev_span, "_".to_string()));
879 idents.push(self.parse_ident()?);
882 if fixed_crate_name {
883 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
884 let mut fixed_name = format!("{}", ident.name);
886 fixed_name.push_str(&format!("_{}", part.name));
888 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
890 self.struct_span_err(fixed_name_sp, error_msg)
891 .span_label(fixed_name_sp, "dash-separated idents are not valid")
892 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
898 /// Parses `extern` for foreign ABIs modules.
900 /// `extern` is expected to have been consumed before calling this method.
904 /// ```ignore (only-for-syntax-highlight)
908 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
909 let abi = self.parse_abi(); // ABI?
910 let items = self.parse_item_list(attrs, |p, _| p.parse_foreign_item())?;
911 let module = ast::ForeignMod { abi, items };
912 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
915 /// Parses a foreign item (one in an `extern { ... }` block).
916 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
917 maybe_whole!(self, NtForeignItem, |item| Some(Some(item)));
919 let attrs = self.parse_outer_attributes()?;
920 let it = self.parse_item_common(attrs, true, false)?;
921 Ok(it.map(|Item { attrs, id, span, vis, ident, defaultness, kind, tokens }| {
922 self.error_on_illegal_default(defaultness);
923 let kind = match kind {
924 ItemKind::Mac(a) => AssocItemKind::Macro(a),
925 ItemKind::Fn(a, b, c) => AssocItemKind::Fn(a, b, c),
926 ItemKind::TyAlias(a, b, c) => AssocItemKind::TyAlias(a, b, c),
927 ItemKind::Static(a, b, c) => AssocItemKind::Static(a, b, c),
928 ItemKind::Const(a, b) => {
929 self.error_on_foreign_const(span, ident);
930 AssocItemKind::Static(a, Mutability::Not, b)
933 let span = self.sess.source_map().def_span(span);
934 self.struct_span_err(span, "item kind not supported in `extern` block").emit();
938 Some(P(Item { attrs, id, span, vis, ident, defaultness, kind, tokens }))
942 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
943 self.struct_span_err(ident.span, "extern items cannot be `const`")
945 span.with_hi(ident.span.lo()),
946 "try using a static value",
947 "static ".to_string(),
948 Applicability::MachineApplicable,
950 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
954 fn is_static_global(&mut self) -> bool {
955 if self.check_keyword(kw::Static) {
956 // Check if this could be a closure.
957 !self.look_ahead(1, |token| {
958 if token.is_keyword(kw::Move) {
962 token::BinOp(token::Or) | token::OrOr => true,
971 /// Recover on `const mut` with `const` already eaten.
972 fn recover_const_mut(&mut self, const_span: Span) {
973 if self.eat_keyword(kw::Mut) {
974 let span = self.prev_span;
975 self.struct_span_err(span, "const globals cannot be mutable")
976 .span_label(span, "cannot be mutable")
979 "you might want to declare a static instead",
981 Applicability::MaybeIncorrect,
987 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
988 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
990 /// When `m` is `"const"`, `$ident` may also be `"_"`.
991 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
992 let (id, ty, expr) = self.parse_item_const_common(m)?;
994 Some(m) => ItemKind::Static(ty, m, expr),
995 None => ItemKind::Const(ty, expr),
1000 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1001 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1003 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1004 fn parse_item_const_common(
1006 m: Option<Mutability>,
1007 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1008 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1010 // Parse the type of a `const` or `static mut?` item.
1011 // That is, the `":" $ty` fragment.
1012 let ty = if self.eat(&token::Colon) {
1015 self.recover_missing_const_type(id, m)
1018 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1019 self.expect_semi()?;
1023 /// We were supposed to parse `:` but the `:` was missing.
1024 /// This means that the type is missing.
1025 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1026 // Construct the error and stash it away with the hope
1027 // that typeck will later enrich the error with a type.
1028 let kind = match m {
1029 Some(Mutability::Mut) => "static mut",
1030 Some(Mutability::Not) => "static",
1033 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1034 err.span_suggestion(
1036 "provide a type for the item",
1037 format!("{}: <type>", id),
1038 Applicability::HasPlaceholders,
1040 err.stash(id.span, StashKey::ItemNoType);
1042 // The user intended that the type be inferred,
1043 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1044 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1047 /// Parses an enum declaration.
1048 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1049 let id = self.parse_ident()?;
1050 let mut generics = self.parse_generics()?;
1051 generics.where_clause = self.parse_where_clause()?;
1054 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1055 self.recover_stmt();
1059 let enum_definition =
1060 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1061 Ok((id, ItemKind::Enum(enum_definition, generics)))
1064 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1065 let variant_attrs = self.parse_outer_attributes()?;
1066 let vlo = self.token.span;
1068 let vis = self.parse_visibility(FollowedByType::No)?;
1069 if !self.recover_nested_adt_item(kw::Enum)? {
1072 let ident = self.parse_ident()?;
1074 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1075 // Parse a struct variant.
1076 let (fields, recovered) = self.parse_record_struct_body()?;
1077 VariantData::Struct(fields, recovered)
1078 } else if self.check(&token::OpenDelim(token::Paren)) {
1079 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1081 VariantData::Unit(DUMMY_NODE_ID)
1085 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1087 let vr = ast::Variant {
1091 attrs: variant_attrs,
1094 span: vlo.to(self.prev_span),
1095 is_placeholder: false,
1101 /// Parses `struct Foo { ... }`.
1102 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1103 let class_name = self.parse_ident()?;
1105 let mut generics = self.parse_generics()?;
1107 // There is a special case worth noting here, as reported in issue #17904.
1108 // If we are parsing a tuple struct it is the case that the where clause
1109 // should follow the field list. Like so:
1111 // struct Foo<T>(T) where T: Copy;
1113 // If we are parsing a normal record-style struct it is the case
1114 // that the where clause comes before the body, and after the generics.
1115 // So if we look ahead and see a brace or a where-clause we begin
1116 // parsing a record style struct.
1118 // Otherwise if we look ahead and see a paren we parse a tuple-style
1121 let vdata = if self.token.is_keyword(kw::Where) {
1122 generics.where_clause = self.parse_where_clause()?;
1123 if self.eat(&token::Semi) {
1124 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1125 VariantData::Unit(DUMMY_NODE_ID)
1127 // If we see: `struct Foo<T> where T: Copy { ... }`
1128 let (fields, recovered) = self.parse_record_struct_body()?;
1129 VariantData::Struct(fields, recovered)
1131 // No `where` so: `struct Foo<T>;`
1132 } else if self.eat(&token::Semi) {
1133 VariantData::Unit(DUMMY_NODE_ID)
1134 // Record-style struct definition
1135 } else if self.token == token::OpenDelim(token::Brace) {
1136 let (fields, recovered) = self.parse_record_struct_body()?;
1137 VariantData::Struct(fields, recovered)
1138 // Tuple-style struct definition with optional where-clause.
1139 } else if self.token == token::OpenDelim(token::Paren) {
1140 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1141 generics.where_clause = self.parse_where_clause()?;
1142 self.expect_semi()?;
1145 let token_str = super::token_descr(&self.token);
1147 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1150 let mut err = self.struct_span_err(self.token.span, msg);
1151 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1155 Ok((class_name, ItemKind::Struct(vdata, generics)))
1158 /// Parses `union Foo { ... }`.
1159 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1160 let class_name = self.parse_ident()?;
1162 let mut generics = self.parse_generics()?;
1164 let vdata = if self.token.is_keyword(kw::Where) {
1165 generics.where_clause = self.parse_where_clause()?;
1166 let (fields, recovered) = self.parse_record_struct_body()?;
1167 VariantData::Struct(fields, recovered)
1168 } else if self.token == token::OpenDelim(token::Brace) {
1169 let (fields, recovered) = self.parse_record_struct_body()?;
1170 VariantData::Struct(fields, recovered)
1172 let token_str = super::token_descr(&self.token);
1173 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1174 let mut err = self.struct_span_err(self.token.span, msg);
1175 err.span_label(self.token.span, "expected `where` or `{` after union name");
1179 Ok((class_name, ItemKind::Union(vdata, generics)))
1182 fn parse_record_struct_body(
1184 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1185 let mut fields = Vec::new();
1186 let mut recovered = false;
1187 if self.eat(&token::OpenDelim(token::Brace)) {
1188 while self.token != token::CloseDelim(token::Brace) {
1189 let field = self.parse_struct_decl_field().map_err(|e| {
1190 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1195 Ok(field) => fields.push(field),
1202 self.eat(&token::CloseDelim(token::Brace));
1204 let token_str = super::token_descr(&self.token);
1205 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1206 let mut err = self.struct_span_err(self.token.span, msg);
1207 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1211 Ok((fields, recovered))
1214 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1215 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1216 // Unit like structs are handled in parse_item_struct function
1217 self.parse_paren_comma_seq(|p| {
1218 let attrs = p.parse_outer_attributes()?;
1219 let lo = p.token.span;
1220 let vis = p.parse_visibility(FollowedByType::Yes)?;
1221 let ty = p.parse_ty()?;
1223 span: lo.to(ty.span),
1229 is_placeholder: false,
1235 /// Parses an element of a struct declaration.
1236 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1237 let attrs = self.parse_outer_attributes()?;
1238 let lo = self.token.span;
1239 let vis = self.parse_visibility(FollowedByType::No)?;
1240 self.parse_single_struct_field(lo, vis, attrs)
1243 /// Parses a structure field declaration.
1244 fn parse_single_struct_field(
1248 attrs: Vec<Attribute>,
1249 ) -> PResult<'a, StructField> {
1250 let mut seen_comma: bool = false;
1251 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1252 if self.token == token::Comma {
1255 match self.token.kind {
1259 token::CloseDelim(token::Brace) => {}
1260 token::DocComment(_) => {
1261 let previous_span = self.prev_span;
1262 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1263 self.bump(); // consume the doc comment
1264 let comma_after_doc_seen = self.eat(&token::Comma);
1265 // `seen_comma` is always false, because we are inside doc block
1266 // condition is here to make code more readable
1267 if seen_comma == false && comma_after_doc_seen == true {
1270 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1273 if seen_comma == false {
1274 let sp = self.sess.source_map().next_point(previous_span);
1275 err.span_suggestion(
1277 "missing comma here",
1279 Applicability::MachineApplicable,
1286 let sp = self.prev_span.shrink_to_hi();
1287 let mut err = self.struct_span_err(
1289 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1291 if self.token.is_ident() {
1292 // This is likely another field; emit the diagnostic and keep going
1293 err.span_suggestion(
1295 "try adding a comma",
1297 Applicability::MachineApplicable,
1308 /// Parses a structure field.
1309 fn parse_name_and_ty(
1313 attrs: Vec<Attribute>,
1314 ) -> PResult<'a, StructField> {
1315 let name = self.parse_ident()?;
1316 self.expect(&token::Colon)?;
1317 let ty = self.parse_ty()?;
1319 span: lo.to(self.prev_span),
1325 is_placeholder: false,
1329 /// Parses a declarative macro 2.0 definition.
1330 /// The `macro` keyword has already been parsed.
1332 /// MacBody = "{" TOKEN_STREAM "}" ;
1333 /// MacParams = "(" TOKEN_STREAM ")" ;
1334 /// DeclMac = "macro" Ident MacParams? MacBody ;
1336 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1337 let ident = self.parse_ident()?;
1338 let body = if self.check(&token::OpenDelim(token::Brace)) {
1339 self.parse_mac_args()? // `MacBody`
1340 } else if self.check(&token::OpenDelim(token::Paren)) {
1341 let params = self.parse_token_tree(); // `MacParams`
1342 let pspan = params.span();
1343 if !self.check(&token::OpenDelim(token::Brace)) {
1344 return self.unexpected();
1346 let body = self.parse_token_tree(); // `MacBody`
1347 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1348 let bspan = body.span();
1349 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1350 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1351 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1352 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1354 return self.unexpected();
1357 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1358 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1361 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1362 fn is_macro_rules_item(&mut self) -> bool {
1363 self.check_keyword(kw::MacroRules)
1364 && self.look_ahead(1, |t| *t == token::Not)
1365 && self.look_ahead(2, |t| t.is_ident())
1368 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1369 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1370 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1371 self.expect(&token::Not)?; // `!`
1373 let ident = self.parse_ident()?;
1374 let body = self.parse_mac_args()?;
1375 self.eat_semi_for_macro_if_needed(&body);
1376 self.complain_if_pub_macro(vis, true);
1378 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1381 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1382 /// If that's not the case, emit an error.
1383 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1384 if let VisibilityKind::Inherited = vis.node {
1388 let vstr = pprust::vis_to_string(vis);
1389 let vstr = vstr.trim_end();
1391 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1392 self.struct_span_err(vis.span, &msg)
1395 "try exporting the macro",
1396 "#[macro_export]".to_owned(),
1397 Applicability::MaybeIncorrect, // speculative
1401 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1404 "remove the visibility",
1406 Applicability::MachineApplicable,
1408 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1413 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1414 if args.need_semicolon() && !self.eat(&token::Semi) {
1415 self.report_invalid_macro_expansion_item(args);
1419 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1420 let span = args.span().expect("undelimited macro call");
1421 let mut err = self.struct_span_err(
1423 "macros that expand to items must be delimited with braces or followed by a semicolon",
1425 if self.unclosed_delims.is_empty() {
1426 let DelimSpan { open, close } = match args {
1427 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1428 MacArgs::Delimited(dspan, ..) => *dspan,
1430 err.multipart_suggestion(
1431 "change the delimiters to curly braces",
1432 vec![(open, "{".to_string()), (close, '}'.to_string())],
1433 Applicability::MaybeIncorrect,
1436 err.span_suggestion(
1438 "change the delimiters to curly braces",
1439 " { /* items */ }".to_string(),
1440 Applicability::HasPlaceholders,
1443 err.span_suggestion(
1444 span.shrink_to_hi(),
1447 Applicability::MaybeIncorrect,
1452 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1453 /// it is, we try to parse the item and report error about nested types.
1454 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1455 if (self.token.is_keyword(kw::Enum)
1456 || self.token.is_keyword(kw::Struct)
1457 || self.token.is_keyword(kw::Union))
1458 && self.look_ahead(1, |t| t.is_ident())
1460 let kw_token = self.token.clone();
1461 let kw_str = pprust::token_to_string(&kw_token);
1462 let item = self.parse_item()?;
1464 self.struct_span_err(
1466 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1470 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1472 Applicability::MaybeIncorrect,
1475 // We successfully parsed the item but we must inform the caller about nested problem.
1487 defaultness: Defaultness,
1488 attrs: Vec<Attribute>,
1490 let span = lo.to(self.prev_span);
1491 Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, defaultness, span, tokens: None }
1495 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1497 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1498 type ReqName = fn(&token::Token) -> bool;
1500 /// Parsing of functions and methods.
1501 impl<'a> Parser<'a> {
1502 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1506 attrs: &mut Vec<Attribute>,
1508 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1509 let header = self.parse_fn_front_matter()?; // `const ... fn`
1510 let ident = self.parse_ident()?; // `foo`
1511 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1512 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1513 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1514 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1515 Ok((ident, FnSig { header, decl }, generics, body))
1518 /// Parse the "body" of a function.
1519 /// This can either be `;` when there's no body,
1520 /// or e.g. a block when the function is a provided one.
1524 attrs: &mut Vec<Attribute>,
1525 ) -> PResult<'a, Option<P<Block>>> {
1526 let (inner_attrs, body) = match self.token.kind {
1531 token::OpenDelim(token::Brace) => {
1532 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1535 token::Interpolated(ref nt) => match **nt {
1536 token::NtBlock(..) => {
1537 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1540 _ => return self.expected_semi_or_open_brace(),
1542 _ => return self.expected_semi_or_open_brace(),
1544 attrs.extend(inner_attrs);
1549 /// Is the current token the start of an `FnHeader` / not a valid parse?
1550 fn check_fn_front_matter(&mut self) -> bool {
1551 // We use an over-approximation here.
1552 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1553 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1554 self.check_keyword(kw::Fn) // Definitely an `fn`.
1555 // `$qual fn` or `$qual $qual`:
1556 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1557 && self.look_ahead(1, |t| {
1558 // ...qualified and then `fn`, e.g. `const fn`.
1559 t.is_keyword(kw::Fn)
1560 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1561 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1564 || self.check_keyword(kw::Extern)
1565 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1566 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1569 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1570 /// up to and including the `fn` keyword. The formal grammar is:
1573 /// Extern = "extern" StringLit ;
1574 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1575 /// FnFrontMatter = FnQual? "fn" ;
1577 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1578 let constness = self.parse_constness();
1579 let asyncness = self.parse_asyncness();
1580 let unsafety = self.parse_unsafety();
1581 let ext = self.parse_extern()?;
1583 if let Async::Yes { span, .. } = asyncness {
1584 self.ban_async_in_2015(span);
1587 if !self.eat_keyword(kw::Fn) {
1588 // It is possible for `expect_one_of` to recover given the contents of
1589 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1590 // account for this.
1591 if !self.expect_one_of(&[], &[])? {
1596 Ok(FnHeader { constness, unsafety, asyncness, ext })
1599 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1600 fn ban_async_in_2015(&self, span: Span) {
1601 if span.rust_2015() {
1602 let diag = self.diagnostic();
1603 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1604 .note("to use `async fn`, switch to Rust 2018")
1605 .help("set `edition = \"2018\"` in `Cargo.toml`")
1606 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1611 /// Parses the parameter list and result type of a function declaration.
1612 pub(super) fn parse_fn_decl(
1615 ret_allow_plus: AllowPlus,
1616 ) -> PResult<'a, P<FnDecl>> {
1618 inputs: self.parse_fn_params(req_name)?,
1619 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1623 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1624 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1625 let mut first_param = true;
1626 // Parse the arguments, starting out with `self` being allowed...
1627 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1628 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1630 let lo = p.prev_span;
1631 // Skip every token until next possible arg or end.
1632 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1633 // Create a placeholder argument for proper arg count (issue #34264).
1634 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1636 // ...now that we've parsed the first argument, `self` is no longer allowed.
1637 first_param = false;
1640 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1641 self.deduplicate_recovered_params_names(&mut params);
1645 /// Parses a single function parameter.
1647 /// - `self` is syntactically allowed when `first_param` holds.
1648 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1649 let lo = self.token.span;
1650 let attrs = self.parse_outer_attributes()?;
1652 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1653 if let Some(mut param) = self.parse_self_param()? {
1654 param.attrs = attrs.into();
1655 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1658 let is_name_required = match self.token.kind {
1659 token::DotDotDot => false,
1660 _ => req_name(&self.token),
1662 let (pat, ty) = if is_name_required || self.is_named_param() {
1663 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1665 let pat = self.parse_fn_param_pat()?;
1666 if let Err(mut err) = self.expect(&token::Colon) {
1667 return if let Some(ident) =
1668 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1671 Ok(dummy_arg(ident))
1677 self.eat_incorrect_doc_comment_for_param_type();
1678 (pat, self.parse_ty_for_param()?)
1680 debug!("parse_param_general ident_to_pat");
1681 let parser_snapshot_before_ty = self.clone();
1682 self.eat_incorrect_doc_comment_for_param_type();
1683 let mut ty = self.parse_ty_for_param();
1685 && self.token != token::Comma
1686 && self.token != token::CloseDelim(token::Paren)
1688 // This wasn't actually a type, but a pattern looking like a type,
1689 // so we are going to rollback and re-parse for recovery.
1690 ty = self.unexpected();
1694 let ident = Ident::new(kw::Invalid, self.prev_span);
1695 let bm = BindingMode::ByValue(Mutability::Not);
1696 let pat = self.mk_pat_ident(ty.span, bm, ident);
1699 // If this is a C-variadic argument and we hit an error, return the error.
1700 Err(err) if self.token == token::DotDotDot => return Err(err),
1701 // Recover from attempting to parse the argument as a type without pattern.
1704 mem::replace(self, parser_snapshot_before_ty);
1705 self.recover_arg_parse()?
1710 let span = lo.to(self.token.span);
1713 attrs: attrs.into(),
1714 id: ast::DUMMY_NODE_ID,
1715 is_placeholder: false,
1722 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1723 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1724 // Extract an identifier *after* having confirmed that the token is one.
1725 let expect_self_ident = |this: &mut Self| {
1726 match this.token.kind {
1727 // Preserve hygienic context.
1728 token::Ident(name, _) => {
1729 let span = this.token.span;
1731 Ident::new(name, span)
1733 _ => unreachable!(),
1736 // Is `self` `n` tokens ahead?
1737 let is_isolated_self = |this: &Self, n| {
1738 this.is_keyword_ahead(n, &[kw::SelfLower])
1739 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1741 // Is `mut self` `n` tokens ahead?
1742 let is_isolated_mut_self =
1743 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1744 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1745 let parse_self_possibly_typed = |this: &mut Self, m| {
1746 let eself_ident = expect_self_ident(this);
1747 let eself_hi = this.prev_span;
1748 let eself = if this.eat(&token::Colon) {
1749 SelfKind::Explicit(this.parse_ty()?, m)
1753 Ok((eself, eself_ident, eself_hi))
1755 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1756 let recover_self_ptr = |this: &mut Self| {
1757 let msg = "cannot pass `self` by raw pointer";
1758 let span = this.token.span;
1759 this.struct_span_err(span, msg).span_label(span, msg).emit();
1761 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1764 // Parse optional `self` parameter of a method.
1765 // Only a limited set of initial token sequences is considered `self` parameters; anything
1766 // else is parsed as a normal function parameter list, so some lookahead is required.
1767 let eself_lo = self.token.span;
1768 let (eself, eself_ident, eself_hi) = match self.token.kind {
1769 token::BinOp(token::And) => {
1770 let eself = if is_isolated_self(self, 1) {
1773 SelfKind::Region(None, Mutability::Not)
1774 } else if is_isolated_mut_self(self, 1) {
1778 SelfKind::Region(None, Mutability::Mut)
1779 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1782 let lt = self.expect_lifetime();
1783 SelfKind::Region(Some(lt), Mutability::Not)
1784 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1787 let lt = self.expect_lifetime();
1789 SelfKind::Region(Some(lt), Mutability::Mut)
1794 (eself, expect_self_ident(self), self.prev_span)
1797 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1799 recover_self_ptr(self)?
1801 // `*mut self` and `*const self`
1802 token::BinOp(token::Star)
1803 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1807 recover_self_ptr(self)?
1809 // `self` and `self: TYPE`
1810 token::Ident(..) if is_isolated_self(self, 0) => {
1811 parse_self_possibly_typed(self, Mutability::Not)?
1813 // `mut self` and `mut self: TYPE`
1814 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1816 parse_self_possibly_typed(self, Mutability::Mut)?
1818 _ => return Ok(None),
1821 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1822 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1825 fn is_named_param(&self) -> bool {
1826 let offset = match self.token.kind {
1827 token::Interpolated(ref nt) => match **nt {
1828 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1831 token::BinOp(token::And) | token::AndAnd => 1,
1832 _ if self.token.is_keyword(kw::Mut) => 1,
1836 self.look_ahead(offset, |t| t.is_ident())
1837 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1840 fn recover_first_param(&mut self) -> &'static str {
1842 .parse_outer_attributes()
1843 .and_then(|_| self.parse_self_param())
1844 .map_err(|mut e| e.cancel())
1846 Ok(Some(_)) => "method",