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()?;
460 let impl_items = self.parse_item_list(attrs, |p, at_end| p.parse_impl_item(at_end))?;
462 let item_kind = match ty_second {
464 // impl Trait for Type
466 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
467 .span_suggestion_short(
471 Applicability::MachineApplicable,
476 let ty_first = ty_first.into_inner();
477 let path = match ty_first.kind {
478 // This notably includes paths passed through `ty` macro fragments (#46438).
479 TyKind::Path(None, path) => path,
481 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
482 err_path(ty_first.span)
485 let trait_ref = TraitRef { path, ref_id: ty_first.id };
493 of_trait: Some(trait_ref),
513 Ok((Ident::invalid(), item_kind))
516 fn parse_item_list<T>(
518 attrs: &mut Vec<Attribute>,
519 mut parse_item: impl FnMut(&mut Parser<'a>, &mut bool) -> PResult<'a, T>,
520 ) -> PResult<'a, Vec<T>> {
521 self.expect(&token::OpenDelim(token::Brace))?;
522 attrs.append(&mut self.parse_inner_attributes()?);
524 let mut items = Vec::new();
525 while !self.eat(&token::CloseDelim(token::Brace)) {
526 if self.recover_doc_comment_before_brace() {
529 let mut at_end = false;
530 match parse_item(self, &mut at_end) {
531 Ok(item) => items.push(item),
535 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
544 /// Recover on a doc comment before `}`.
545 fn recover_doc_comment_before_brace(&mut self) -> bool {
546 if let token::DocComment(_) = self.token.kind {
547 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
552 "found a documentation comment that doesn't document anything",
554 .span_label(self.token.span, "this doc comment doesn't document anything")
556 "doc comments must come before what they document, maybe a \
557 comment was intended with `//`?",
567 /// Parses defaultness (i.e., `default` or nothing).
568 fn parse_defaultness(&mut self) -> Defaultness {
569 // We are interested in `default` followed by another identifier.
570 // However, we must avoid keywords that occur as binary operators.
571 // Currently, the only applicable keyword is `as` (`default as Ty`).
572 if self.check_keyword(kw::Default)
573 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
575 self.bump(); // `default`
576 Defaultness::Default(self.prev_span)
582 /// Is this an `(unsafe auto? | auto) trait` item?
583 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
585 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
587 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
590 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
591 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
592 let unsafety = self.parse_unsafety();
593 // Parse optional `auto` prefix.
594 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
596 self.expect_keyword(kw::Trait)?;
597 let ident = self.parse_ident()?;
598 let mut tps = self.parse_generics()?;
600 // Parse optional colon and supertrait bounds.
601 let had_colon = self.eat(&token::Colon);
602 let span_at_colon = self.prev_span;
604 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
606 let span_before_eq = self.prev_span;
607 if self.eat(&token::Eq) {
608 // It's a trait alias.
610 let span = span_at_colon.to(span_before_eq);
611 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
614 let bounds = self.parse_generic_bounds(None)?;
615 tps.where_clause = self.parse_where_clause()?;
618 let whole_span = lo.to(self.prev_span);
619 if is_auto == IsAuto::Yes {
620 let msg = "trait aliases cannot be `auto`";
621 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
623 if let Unsafe::Yes(_) = unsafety {
624 let msg = "trait aliases cannot be `unsafe`";
625 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
628 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
630 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
632 // It's a normal trait.
633 tps.where_clause = self.parse_where_clause()?;
634 let items = self.parse_item_list(attrs, |p, at_end| p.parse_trait_item(at_end))?;
635 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
639 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
640 maybe_whole!(self, NtImplItem, |x| x);
641 self.parse_assoc_item(at_end, |_| true)
644 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
645 maybe_whole!(self, NtTraitItem, |x| x);
646 // This is somewhat dubious; We don't want to allow
647 // param names to be left off if there is a definition...
649 // We don't allow param names to be left off in edition 2018.
650 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
653 /// Parses associated items.
658 ) -> PResult<'a, P<AssocItem>> {
659 let attrs = self.parse_outer_attributes()?;
660 let mut unclosed_delims = vec![];
661 let (mut item, tokens) = self.collect_tokens(|this| {
662 let item = this.parse_assoc_item_(at_end, attrs, req_name);
663 unclosed_delims.append(&mut this.unclosed_delims);
666 self.unclosed_delims.append(&mut unclosed_delims);
667 // See `parse_item` for why this clause is here.
668 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
669 item.tokens = Some(tokens);
671 self.error_on_assoc_static(&item);
675 fn error_on_assoc_static(&self, item: &AssocItem) {
676 if let AssocItemKind::Static(..) = item.kind {
677 self.struct_span_err(item.span, "associated `static` items are not allowed").emit();
681 fn parse_assoc_item_(
684 mut attrs: Vec<Attribute>,
686 ) -> PResult<'a, AssocItem> {
687 let lo = self.token.span;
688 let vis = self.parse_visibility(FollowedByType::No)?;
689 let defaultness = self.parse_defaultness();
690 let (ident, kind) = self.parse_assoc_item_kind(at_end, &mut attrs, req_name, &vis)?;
691 let span = lo.to(self.prev_span);
692 let id = DUMMY_NODE_ID;
693 Ok(AssocItem { id, span, ident, attrs, vis, defaultness, kind, tokens: None })
696 fn parse_assoc_item_kind(
699 attrs: &mut Vec<Attribute>,
702 ) -> PResult<'a, (Ident, AssocItemKind)> {
703 if self.eat_keyword(kw::Type) {
704 match self.parse_type_alias()? {
705 (ident, ItemKind::TyAlias(a, b, c)) => Ok((ident, AssocItemKind::TyAlias(a, b, c))),
708 } else if self.check_fn_front_matter() {
709 let (ident, sig, generics, body) = self.parse_fn(at_end, attrs, req_name)?;
710 Ok((ident, AssocItemKind::Fn(sig, generics, body)))
711 } else if self.is_static_global() {
712 self.bump(); // `static`
713 let mutbl = self.parse_mutability();
714 let (ident, ty, expr) = self.parse_item_const_common(Some(mutbl))?;
715 Ok((ident, AssocItemKind::Static(ty, mutbl, expr)))
716 } else if self.eat_keyword(kw::Const) {
717 let (ident, ty, expr) = self.parse_item_const_common(None)?;
718 Ok((ident, AssocItemKind::Const(ty, expr)))
719 } else if self.isnt_macro_invocation() {
720 Err(self.missing_nested_item_kind_err(self.prev_span))
721 } else if self.token.is_path_start() {
722 let mac = self.parse_item_macro(&vis)?;
724 Ok((Ident::invalid(), AssocItemKind::Macro(mac)))
726 self.recover_attrs_no_item(attrs)?;
731 /// Parses a `type` alias with the following grammar:
733 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
735 /// The `"type"` has already been eaten.
736 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, ItemKind)> {
737 let ident = self.parse_ident()?;
738 let mut generics = self.parse_generics()?;
740 // Parse optional colon and param bounds.
742 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
743 generics.where_clause = self.parse_where_clause()?;
745 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
748 Ok((ident, ItemKind::TyAlias(generics, bounds, default)))
751 /// Parses a `UseTree`.
754 /// USE_TREE = [`::`] `*` |
755 /// [`::`] `{` USE_TREE_LIST `}` |
757 /// PATH `::` `{` USE_TREE_LIST `}` |
758 /// PATH [`as` IDENT]
760 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
761 let lo = self.token.span;
763 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
764 let kind = if self.check(&token::OpenDelim(token::Brace))
765 || self.check(&token::BinOp(token::Star))
766 || self.is_import_coupler()
768 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
769 let mod_sep_ctxt = self.token.span.ctxt();
770 if self.eat(&token::ModSep) {
773 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
776 self.parse_use_tree_glob_or_nested()?
778 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
779 prefix = self.parse_path(PathStyle::Mod)?;
781 if self.eat(&token::ModSep) {
782 self.parse_use_tree_glob_or_nested()?
784 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
788 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
791 /// Parses `*` or `{...}`.
792 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
793 Ok(if self.eat(&token::BinOp(token::Star)) {
796 UseTreeKind::Nested(self.parse_use_tree_list()?)
800 /// Parses a `UseTreeKind::Nested(list)`.
803 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
805 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
806 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
810 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
811 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
814 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
815 match self.token.kind {
816 token::Ident(name @ kw::Underscore, false) => {
817 let span = self.token.span;
819 Ok(Ident::new(name, span))
821 _ => self.parse_ident(),
825 /// Parses `extern crate` links.
830 /// extern crate foo;
831 /// extern crate bar as foo;
833 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
834 // Accept `extern crate name-like-this` for better diagnostics
835 let orig_name = self.parse_crate_name_with_dashes()?;
836 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
837 (rename, Some(orig_name.name))
842 Ok((item_name, ItemKind::ExternCrate(orig_name)))
845 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
846 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
847 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
849 let mut ident = if self.token.is_keyword(kw::SelfLower) {
850 self.parse_path_segment_ident()
854 let mut idents = vec![];
855 let mut replacement = vec![];
856 let mut fixed_crate_name = false;
857 // Accept `extern crate name-like-this` for better diagnostics.
858 let dash = token::BinOp(token::BinOpToken::Minus);
859 if self.token == dash {
860 // Do not include `-` as part of the expected tokens list.
861 while self.eat(&dash) {
862 fixed_crate_name = true;
863 replacement.push((self.prev_span, "_".to_string()));
864 idents.push(self.parse_ident()?);
867 if fixed_crate_name {
868 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
869 let mut fixed_name = format!("{}", ident.name);
871 fixed_name.push_str(&format!("_{}", part.name));
873 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
875 self.struct_span_err(fixed_name_sp, error_msg)
876 .span_label(fixed_name_sp, "dash-separated idents are not valid")
877 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
883 /// Parses `extern` for foreign ABIs modules.
885 /// `extern` is expected to have been consumed before calling this method.
889 /// ```ignore (only-for-syntax-highlight)
893 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
894 let abi = self.parse_abi(); // ABI?
895 let items = self.parse_item_list(attrs, |p, at_end| p.parse_foreign_item(at_end))?;
896 let module = ast::ForeignMod { abi, items };
897 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
900 /// Parses a foreign item (one in an `extern { ... }` block).
901 pub fn parse_foreign_item(&mut self, at_end: &mut bool) -> PResult<'a, P<ForeignItem>> {
902 maybe_whole!(self, NtForeignItem, |ni| ni);
904 let mut attrs = self.parse_outer_attributes()?;
905 let lo = self.token.span;
906 let vis = self.parse_visibility(FollowedByType::No)?;
907 let (ident, kind) = self.parse_assoc_item_kind(at_end, &mut attrs, |_| true, &vis)?;
908 let item = self.mk_item(lo, ident, kind, vis, Defaultness::Final, attrs);
909 self.error_on_foreign_const(&item);
913 fn error_on_foreign_const(&self, item: &ForeignItem) {
914 if let AssocItemKind::Const(..) = item.kind {
915 self.struct_span_err(item.ident.span, "extern items cannot be `const`")
917 item.span.with_hi(item.ident.span.lo()),
918 "try using a static value",
919 "static ".to_string(),
920 Applicability::MachineApplicable,
923 "for more information, visit https://doc.rust-lang.org/std/keyword.extern.html",
929 fn is_static_global(&mut self) -> bool {
930 if self.check_keyword(kw::Static) {
931 // Check if this could be a closure.
932 !self.look_ahead(1, |token| {
933 if token.is_keyword(kw::Move) {
937 token::BinOp(token::Or) | token::OrOr => true,
946 /// Recover on `const mut` with `const` already eaten.
947 fn recover_const_mut(&mut self, const_span: Span) {
948 if self.eat_keyword(kw::Mut) {
949 let span = self.prev_span;
950 self.struct_span_err(span, "const globals cannot be mutable")
951 .span_label(span, "cannot be mutable")
954 "you might want to declare a static instead",
956 Applicability::MaybeIncorrect,
962 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
963 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
965 /// When `m` is `"const"`, `$ident` may also be `"_"`.
966 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
967 let (id, ty, expr) = self.parse_item_const_common(m)?;
969 Some(m) => ItemKind::Static(ty, m, expr),
970 None => ItemKind::Const(ty, expr),
975 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
976 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
978 /// When `m` is `"const"`, `$ident` may also be `"_"`.
979 fn parse_item_const_common(
981 m: Option<Mutability>,
982 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
983 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
985 // Parse the type of a `const` or `static mut?` item.
986 // That is, the `":" $ty` fragment.
987 let ty = if self.eat(&token::Colon) {
990 self.recover_missing_const_type(id, m)
993 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
998 /// We were supposed to parse `:` but the `:` was missing.
999 /// This means that the type is missing.
1000 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1001 // Construct the error and stash it away with the hope
1002 // that typeck will later enrich the error with a type.
1003 let kind = match m {
1004 Some(Mutability::Mut) => "static mut",
1005 Some(Mutability::Not) => "static",
1008 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1009 err.span_suggestion(
1011 "provide a type for the item",
1012 format!("{}: <type>", id),
1013 Applicability::HasPlaceholders,
1015 err.stash(id.span, StashKey::ItemNoType);
1017 // The user intended that the type be inferred,
1018 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1019 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1022 /// Parses an enum declaration.
1023 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1024 let id = self.parse_ident()?;
1025 let mut generics = self.parse_generics()?;
1026 generics.where_clause = self.parse_where_clause()?;
1029 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1030 self.recover_stmt();
1034 let enum_definition =
1035 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1036 Ok((id, ItemKind::Enum(enum_definition, generics)))
1039 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1040 let variant_attrs = self.parse_outer_attributes()?;
1041 let vlo = self.token.span;
1043 let vis = self.parse_visibility(FollowedByType::No)?;
1044 if !self.recover_nested_adt_item(kw::Enum)? {
1047 let ident = self.parse_ident()?;
1049 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1050 // Parse a struct variant.
1051 let (fields, recovered) = self.parse_record_struct_body()?;
1052 VariantData::Struct(fields, recovered)
1053 } else if self.check(&token::OpenDelim(token::Paren)) {
1054 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1056 VariantData::Unit(DUMMY_NODE_ID)
1060 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1062 let vr = ast::Variant {
1066 attrs: variant_attrs,
1069 span: vlo.to(self.prev_span),
1070 is_placeholder: false,
1076 /// Parses `struct Foo { ... }`.
1077 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1078 let class_name = self.parse_ident()?;
1080 let mut generics = self.parse_generics()?;
1082 // There is a special case worth noting here, as reported in issue #17904.
1083 // If we are parsing a tuple struct it is the case that the where clause
1084 // should follow the field list. Like so:
1086 // struct Foo<T>(T) where T: Copy;
1088 // If we are parsing a normal record-style struct it is the case
1089 // that the where clause comes before the body, and after the generics.
1090 // So if we look ahead and see a brace or a where-clause we begin
1091 // parsing a record style struct.
1093 // Otherwise if we look ahead and see a paren we parse a tuple-style
1096 let vdata = if self.token.is_keyword(kw::Where) {
1097 generics.where_clause = self.parse_where_clause()?;
1098 if self.eat(&token::Semi) {
1099 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1100 VariantData::Unit(DUMMY_NODE_ID)
1102 // If we see: `struct Foo<T> where T: Copy { ... }`
1103 let (fields, recovered) = self.parse_record_struct_body()?;
1104 VariantData::Struct(fields, recovered)
1106 // No `where` so: `struct Foo<T>;`
1107 } else if self.eat(&token::Semi) {
1108 VariantData::Unit(DUMMY_NODE_ID)
1109 // Record-style struct definition
1110 } else if self.token == token::OpenDelim(token::Brace) {
1111 let (fields, recovered) = self.parse_record_struct_body()?;
1112 VariantData::Struct(fields, recovered)
1113 // Tuple-style struct definition with optional where-clause.
1114 } else if self.token == token::OpenDelim(token::Paren) {
1115 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1116 generics.where_clause = self.parse_where_clause()?;
1117 self.expect_semi()?;
1120 let token_str = super::token_descr(&self.token);
1122 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1125 let mut err = self.struct_span_err(self.token.span, msg);
1126 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1130 Ok((class_name, ItemKind::Struct(vdata, generics)))
1133 /// Parses `union Foo { ... }`.
1134 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1135 let class_name = self.parse_ident()?;
1137 let mut generics = self.parse_generics()?;
1139 let vdata = if self.token.is_keyword(kw::Where) {
1140 generics.where_clause = self.parse_where_clause()?;
1141 let (fields, recovered) = self.parse_record_struct_body()?;
1142 VariantData::Struct(fields, recovered)
1143 } else if self.token == token::OpenDelim(token::Brace) {
1144 let (fields, recovered) = self.parse_record_struct_body()?;
1145 VariantData::Struct(fields, recovered)
1147 let token_str = super::token_descr(&self.token);
1148 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1149 let mut err = self.struct_span_err(self.token.span, msg);
1150 err.span_label(self.token.span, "expected `where` or `{` after union name");
1154 Ok((class_name, ItemKind::Union(vdata, generics)))
1157 fn parse_record_struct_body(
1159 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1160 let mut fields = Vec::new();
1161 let mut recovered = false;
1162 if self.eat(&token::OpenDelim(token::Brace)) {
1163 while self.token != token::CloseDelim(token::Brace) {
1164 let field = self.parse_struct_decl_field().map_err(|e| {
1165 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1170 Ok(field) => fields.push(field),
1177 self.eat(&token::CloseDelim(token::Brace));
1179 let token_str = super::token_descr(&self.token);
1180 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1181 let mut err = self.struct_span_err(self.token.span, msg);
1182 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1186 Ok((fields, recovered))
1189 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1190 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1191 // Unit like structs are handled in parse_item_struct function
1192 self.parse_paren_comma_seq(|p| {
1193 let attrs = p.parse_outer_attributes()?;
1194 let lo = p.token.span;
1195 let vis = p.parse_visibility(FollowedByType::Yes)?;
1196 let ty = p.parse_ty()?;
1198 span: lo.to(ty.span),
1204 is_placeholder: false,
1210 /// Parses an element of a struct declaration.
1211 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1212 let attrs = self.parse_outer_attributes()?;
1213 let lo = self.token.span;
1214 let vis = self.parse_visibility(FollowedByType::No)?;
1215 self.parse_single_struct_field(lo, vis, attrs)
1218 /// Parses a structure field declaration.
1219 fn parse_single_struct_field(
1223 attrs: Vec<Attribute>,
1224 ) -> PResult<'a, StructField> {
1225 let mut seen_comma: bool = false;
1226 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1227 if self.token == token::Comma {
1230 match self.token.kind {
1234 token::CloseDelim(token::Brace) => {}
1235 token::DocComment(_) => {
1236 let previous_span = self.prev_span;
1237 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1238 self.bump(); // consume the doc comment
1239 let comma_after_doc_seen = self.eat(&token::Comma);
1240 // `seen_comma` is always false, because we are inside doc block
1241 // condition is here to make code more readable
1242 if seen_comma == false && comma_after_doc_seen == true {
1245 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1248 if seen_comma == false {
1249 let sp = self.sess.source_map().next_point(previous_span);
1250 err.span_suggestion(
1252 "missing comma here",
1254 Applicability::MachineApplicable,
1261 let sp = self.prev_span.shrink_to_hi();
1262 let mut err = self.struct_span_err(
1264 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1266 if self.token.is_ident() {
1267 // This is likely another field; emit the diagnostic and keep going
1268 err.span_suggestion(
1270 "try adding a comma",
1272 Applicability::MachineApplicable,
1283 /// Parses a structure field.
1284 fn parse_name_and_ty(
1288 attrs: Vec<Attribute>,
1289 ) -> PResult<'a, StructField> {
1290 let name = self.parse_ident()?;
1291 self.expect(&token::Colon)?;
1292 let ty = self.parse_ty()?;
1294 span: lo.to(self.prev_span),
1300 is_placeholder: false,
1304 /// Parses a declarative macro 2.0 definition.
1305 /// The `macro` keyword has already been parsed.
1307 /// MacBody = "{" TOKEN_STREAM "}" ;
1308 /// MacParams = "(" TOKEN_STREAM ")" ;
1309 /// DeclMac = "macro" Ident MacParams? MacBody ;
1311 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1312 let ident = self.parse_ident()?;
1313 let body = if self.check(&token::OpenDelim(token::Brace)) {
1314 self.parse_mac_args()? // `MacBody`
1315 } else if self.check(&token::OpenDelim(token::Paren)) {
1316 let params = self.parse_token_tree(); // `MacParams`
1317 let pspan = params.span();
1318 if !self.check(&token::OpenDelim(token::Brace)) {
1319 return self.unexpected();
1321 let body = self.parse_token_tree(); // `MacBody`
1322 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1323 let bspan = body.span();
1324 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1325 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1326 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1327 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1329 return self.unexpected();
1332 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1333 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1336 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1337 fn is_macro_rules_item(&mut self) -> bool {
1338 self.check_keyword(kw::MacroRules)
1339 && self.look_ahead(1, |t| *t == token::Not)
1340 && self.look_ahead(2, |t| t.is_ident())
1343 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1344 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1345 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1346 self.expect(&token::Not)?; // `!`
1348 let ident = self.parse_ident()?;
1349 let body = self.parse_mac_args()?;
1350 self.eat_semi_for_macro_if_needed(&body);
1351 self.complain_if_pub_macro(vis, true);
1353 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1356 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1357 /// If that's not the case, emit an error.
1358 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1359 if let VisibilityKind::Inherited = vis.node {
1363 let vstr = pprust::vis_to_string(vis);
1364 let vstr = vstr.trim_end();
1366 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1367 self.struct_span_err(vis.span, &msg)
1370 "try exporting the macro",
1371 "#[macro_export]".to_owned(),
1372 Applicability::MaybeIncorrect, // speculative
1376 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1379 "remove the visibility",
1381 Applicability::MachineApplicable,
1383 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1388 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1389 if args.need_semicolon() && !self.eat(&token::Semi) {
1390 self.report_invalid_macro_expansion_item(args);
1394 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1395 let span = args.span().expect("undelimited macro call");
1396 let mut err = self.struct_span_err(
1398 "macros that expand to items must be delimited with braces or followed by a semicolon",
1400 if self.unclosed_delims.is_empty() {
1401 let DelimSpan { open, close } = match args {
1402 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1403 MacArgs::Delimited(dspan, ..) => *dspan,
1405 err.multipart_suggestion(
1406 "change the delimiters to curly braces",
1407 vec![(open, "{".to_string()), (close, '}'.to_string())],
1408 Applicability::MaybeIncorrect,
1411 err.span_suggestion(
1413 "change the delimiters to curly braces",
1414 " { /* items */ }".to_string(),
1415 Applicability::HasPlaceholders,
1418 err.span_suggestion(
1419 span.shrink_to_hi(),
1422 Applicability::MaybeIncorrect,
1427 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1428 /// it is, we try to parse the item and report error about nested types.
1429 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1430 if (self.token.is_keyword(kw::Enum)
1431 || self.token.is_keyword(kw::Struct)
1432 || self.token.is_keyword(kw::Union))
1433 && self.look_ahead(1, |t| t.is_ident())
1435 let kw_token = self.token.clone();
1436 let kw_str = pprust::token_to_string(&kw_token);
1437 let item = self.parse_item()?;
1439 self.struct_span_err(
1441 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1445 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1447 Applicability::MaybeIncorrect,
1450 // We successfully parsed the item but we must inform the caller about nested problem.
1462 defaultness: Defaultness,
1463 attrs: Vec<Attribute>,
1465 let span = lo.to(self.prev_span);
1466 Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, defaultness, span, tokens: None }
1470 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1472 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1473 type ReqName = fn(&token::Token) -> bool;
1475 /// Parsing of functions and methods.
1476 impl<'a> Parser<'a> {
1477 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1481 attrs: &mut Vec<Attribute>,
1483 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1484 let header = self.parse_fn_front_matter()?; // `const ... fn`
1485 let ident = self.parse_ident()?; // `foo`
1486 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1487 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1488 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1489 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1490 Ok((ident, FnSig { header, decl }, generics, body))
1493 /// Parse the "body" of a function.
1494 /// This can either be `;` when there's no body,
1495 /// or e.g. a block when the function is a provided one.
1499 attrs: &mut Vec<Attribute>,
1500 ) -> PResult<'a, Option<P<Block>>> {
1501 let (inner_attrs, body) = match self.token.kind {
1506 token::OpenDelim(token::Brace) => {
1507 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1510 token::Interpolated(ref nt) => match **nt {
1511 token::NtBlock(..) => {
1512 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1515 _ => return self.expected_semi_or_open_brace(),
1517 _ => return self.expected_semi_or_open_brace(),
1519 attrs.extend(inner_attrs);
1524 /// Is the current token the start of an `FnHeader` / not a valid parse?
1525 fn check_fn_front_matter(&mut self) -> bool {
1526 // We use an over-approximation here.
1527 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1528 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1529 self.check_keyword(kw::Fn) // Definitely an `fn`.
1530 // `$qual fn` or `$qual $qual`:
1531 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1532 && self.look_ahead(1, |t| {
1533 // ...qualified and then `fn`, e.g. `const fn`.
1534 t.is_keyword(kw::Fn)
1535 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1536 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1539 || self.check_keyword(kw::Extern)
1540 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1541 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1544 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1545 /// up to and including the `fn` keyword. The formal grammar is:
1548 /// Extern = "extern" StringLit ;
1549 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1550 /// FnFrontMatter = FnQual? "fn" ;
1552 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1553 let constness = self.parse_constness();
1554 let asyncness = self.parse_asyncness();
1555 let unsafety = self.parse_unsafety();
1556 let ext = self.parse_extern()?;
1558 if let Async::Yes { span, .. } = asyncness {
1559 self.ban_async_in_2015(span);
1562 if !self.eat_keyword(kw::Fn) {
1563 // It is possible for `expect_one_of` to recover given the contents of
1564 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1565 // account for this.
1566 if !self.expect_one_of(&[], &[])? {
1571 Ok(FnHeader { constness, unsafety, asyncness, ext })
1574 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1575 fn ban_async_in_2015(&self, span: Span) {
1576 if span.rust_2015() {
1577 let diag = self.diagnostic();
1578 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1579 .note("to use `async fn`, switch to Rust 2018")
1580 .help("set `edition = \"2018\"` in `Cargo.toml`")
1581 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1586 /// Parses the parameter list and result type of a function declaration.
1587 pub(super) fn parse_fn_decl(
1590 ret_allow_plus: AllowPlus,
1591 ) -> PResult<'a, P<FnDecl>> {
1593 inputs: self.parse_fn_params(req_name)?,
1594 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1598 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1599 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1600 let mut first_param = true;
1601 // Parse the arguments, starting out with `self` being allowed...
1602 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1603 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1605 let lo = p.prev_span;
1606 // Skip every token until next possible arg or end.
1607 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1608 // Create a placeholder argument for proper arg count (issue #34264).
1609 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1611 // ...now that we've parsed the first argument, `self` is no longer allowed.
1612 first_param = false;
1615 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1616 self.deduplicate_recovered_params_names(&mut params);
1620 /// Parses a single function parameter.
1622 /// - `self` is syntactically allowed when `first_param` holds.
1623 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1624 let lo = self.token.span;
1625 let attrs = self.parse_outer_attributes()?;
1627 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1628 if let Some(mut param) = self.parse_self_param()? {
1629 param.attrs = attrs.into();
1630 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1633 let is_name_required = match self.token.kind {
1634 token::DotDotDot => false,
1635 _ => req_name(&self.token),
1637 let (pat, ty) = if is_name_required || self.is_named_param() {
1638 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1640 let pat = self.parse_fn_param_pat()?;
1641 if let Err(mut err) = self.expect(&token::Colon) {
1642 return if let Some(ident) =
1643 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1646 Ok(dummy_arg(ident))
1652 self.eat_incorrect_doc_comment_for_param_type();
1653 (pat, self.parse_ty_for_param()?)
1655 debug!("parse_param_general ident_to_pat");
1656 let parser_snapshot_before_ty = self.clone();
1657 self.eat_incorrect_doc_comment_for_param_type();
1658 let mut ty = self.parse_ty_for_param();
1660 && self.token != token::Comma
1661 && self.token != token::CloseDelim(token::Paren)
1663 // This wasn't actually a type, but a pattern looking like a type,
1664 // so we are going to rollback and re-parse for recovery.
1665 ty = self.unexpected();
1669 let ident = Ident::new(kw::Invalid, self.prev_span);
1670 let bm = BindingMode::ByValue(Mutability::Not);
1671 let pat = self.mk_pat_ident(ty.span, bm, ident);
1674 // If this is a C-variadic argument and we hit an error, return the error.
1675 Err(err) if self.token == token::DotDotDot => return Err(err),
1676 // Recover from attempting to parse the argument as a type without pattern.
1679 mem::replace(self, parser_snapshot_before_ty);
1680 self.recover_arg_parse()?
1685 let span = lo.to(self.token.span);
1688 attrs: attrs.into(),
1689 id: ast::DUMMY_NODE_ID,
1690 is_placeholder: false,
1697 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1698 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1699 // Extract an identifier *after* having confirmed that the token is one.
1700 let expect_self_ident = |this: &mut Self| {
1701 match this.token.kind {
1702 // Preserve hygienic context.
1703 token::Ident(name, _) => {
1704 let span = this.token.span;
1706 Ident::new(name, span)
1708 _ => unreachable!(),
1711 // Is `self` `n` tokens ahead?
1712 let is_isolated_self = |this: &Self, n| {
1713 this.is_keyword_ahead(n, &[kw::SelfLower])
1714 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1716 // Is `mut self` `n` tokens ahead?
1717 let is_isolated_mut_self =
1718 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1719 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1720 let parse_self_possibly_typed = |this: &mut Self, m| {
1721 let eself_ident = expect_self_ident(this);
1722 let eself_hi = this.prev_span;
1723 let eself = if this.eat(&token::Colon) {
1724 SelfKind::Explicit(this.parse_ty()?, m)
1728 Ok((eself, eself_ident, eself_hi))
1730 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1731 let recover_self_ptr = |this: &mut Self| {
1732 let msg = "cannot pass `self` by raw pointer";
1733 let span = this.token.span;
1734 this.struct_span_err(span, msg).span_label(span, msg).emit();
1736 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1739 // Parse optional `self` parameter of a method.
1740 // Only a limited set of initial token sequences is considered `self` parameters; anything
1741 // else is parsed as a normal function parameter list, so some lookahead is required.
1742 let eself_lo = self.token.span;
1743 let (eself, eself_ident, eself_hi) = match self.token.kind {
1744 token::BinOp(token::And) => {
1745 let eself = if is_isolated_self(self, 1) {
1748 SelfKind::Region(None, Mutability::Not)
1749 } else if is_isolated_mut_self(self, 1) {
1753 SelfKind::Region(None, Mutability::Mut)
1754 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1757 let lt = self.expect_lifetime();
1758 SelfKind::Region(Some(lt), Mutability::Not)
1759 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1762 let lt = self.expect_lifetime();
1764 SelfKind::Region(Some(lt), Mutability::Mut)
1769 (eself, expect_self_ident(self), self.prev_span)
1772 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1774 recover_self_ptr(self)?
1776 // `*mut self` and `*const self`
1777 token::BinOp(token::Star)
1778 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1782 recover_self_ptr(self)?
1784 // `self` and `self: TYPE`
1785 token::Ident(..) if is_isolated_self(self, 0) => {
1786 parse_self_possibly_typed(self, Mutability::Not)?
1788 // `mut self` and `mut self: TYPE`
1789 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1791 parse_self_possibly_typed(self, Mutability::Mut)?
1793 _ => return Ok(None),
1796 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1797 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1800 fn is_named_param(&self) -> bool {
1801 let offset = match self.token.kind {
1802 token::Interpolated(ref nt) => match **nt {
1803 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1806 token::BinOp(token::And) | token::AndAnd => 1,
1807 _ if self.token.is_keyword(kw::Mut) => 1,
1811 self.look_ahead(offset, |t| t.is_ident())
1812 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1815 fn recover_first_param(&mut self) -> &'static str {
1817 .parse_outer_attributes()
1818 .and_then(|_| self.parse_self_param())
1819 .map_err(|mut e| e.cancel())
1821 Ok(Some(_)) => "method",