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 rustc_span::BytePos;
12 use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
13 use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind};
14 use syntax::ast::{Async, Const, Defaultness, IsAuto, PathSegment, StrLit, Unsafe};
15 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
16 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
17 use syntax::ast::{FnHeader, ForeignItem, ForeignItemKind, Mutability, Visibility, VisibilityKind};
20 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
25 pub(super) type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
28 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
29 let attrs = self.parse_outer_attributes()?;
30 self.parse_item_(attrs, true, false)
33 pub(super) fn parse_item_(
35 attrs: Vec<Attribute>,
37 attributes_allowed: bool,
38 ) -> PResult<'a, Option<P<Item>>> {
39 let mut unclosed_delims = vec![];
40 let (ret, tokens) = self.collect_tokens(|this| {
41 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
42 unclosed_delims.append(&mut this.unclosed_delims);
45 self.unclosed_delims.append(&mut unclosed_delims);
47 // Once we've parsed an item and recorded the tokens we got while
48 // parsing we may want to store `tokens` into the item we're about to
49 // return. Note, though, that we specifically didn't capture tokens
50 // related to outer attributes. The `tokens` field here may later be
51 // used with procedural macros to convert this item back into a token
52 // stream, but during expansion we may be removing attributes as we go
55 // If we've got inner attributes then the `tokens` we've got above holds
56 // these inner attributes. If an inner attribute is expanded we won't
57 // actually remove it from the token stream, so we'll just keep yielding
58 // it (bad!). To work around this case for now we just avoid recording
59 // `tokens` if we detect any inner attributes. This should help keep
60 // expansion correct, but we should fix this bug one day!
63 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
64 i.tokens = Some(tokens);
71 /// Parses one of the items allowed by the flags.
72 fn parse_item_implementation(
74 mut attrs: Vec<Attribute>,
76 attributes_allowed: bool,
77 ) -> PResult<'a, Option<P<Item>>> {
78 maybe_whole!(self, NtItem, |item| {
80 mem::swap(&mut item.attrs, &mut attrs);
81 item.attrs.extend(attrs);
85 let lo = self.token.span;
87 let vis = self.parse_visibility(FollowedByType::No)?;
89 if self.eat_keyword(kw::Use) {
91 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
94 let span = lo.to(self.prev_span);
95 let item = self.mk_item(span, Ident::invalid(), item_, vis, attrs);
96 return Ok(Some(item));
99 if self.check_fn_front_matter() {
101 let (ident, sig, generics, body) = self.parse_fn(&mut false, &mut attrs, |_| true)?;
102 let kind = ItemKind::Fn(sig, generics, body);
103 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
106 if self.eat_keyword(kw::Extern) {
107 if self.eat_keyword(kw::Crate) {
109 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
112 let abi = self.parse_abi();
113 return Ok(Some(self.parse_item_foreign_mod(lo, abi, vis, attrs)?));
116 if self.is_static_global() {
119 let m = self.parse_mutability();
120 let info = self.parse_item_const(Some(m))?;
121 return self.mk_item_with_info(attrs, lo, vis, info);
124 if let Const::Yes(const_span) = self.parse_constness() {
126 if self.eat_keyword(kw::Mut) {
127 let prev_span = self.prev_span;
128 self.struct_span_err(prev_span, "const globals cannot be mutable")
129 .span_label(prev_span, "cannot be mutable")
132 "you might want to declare a static instead",
134 Applicability::MaybeIncorrect,
139 let info = self.parse_item_const(None)?;
140 return self.mk_item_with_info(attrs, lo, vis, info);
143 if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) {
145 let unsafety = self.parse_unsafety();
146 let info = self.parse_item_trait(lo, unsafety)?;
147 return self.mk_item_with_info(attrs, lo, vis, info);
150 if self.check_keyword(kw::Impl)
151 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
152 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
155 let defaultness = self.parse_defaultness();
156 let unsafety = self.parse_unsafety();
157 self.expect_keyword(kw::Impl)?;
158 let info = self.parse_item_impl(unsafety, defaultness)?;
159 return self.mk_item_with_info(attrs, lo, vis, info);
162 if self.eat_keyword(kw::Mod) {
164 let info = self.parse_item_mod(&attrs[..])?;
165 return self.mk_item_with_info(attrs, lo, vis, info);
168 if self.eat_keyword(kw::Type) {
170 let (ident, ty, generics) = self.parse_type_alias()?;
171 let kind = ItemKind::TyAlias(ty, generics);
172 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
175 if self.eat_keyword(kw::Enum) {
177 let info = self.parse_item_enum()?;
178 return self.mk_item_with_info(attrs, lo, vis, info);
181 if self.check_keyword(kw::Trait)
182 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
185 let info = self.parse_item_trait(lo, Unsafe::No)?;
186 return self.mk_item_with_info(attrs, lo, vis, info);
189 if self.eat_keyword(kw::Struct) {
191 let info = self.parse_item_struct()?;
192 return self.mk_item_with_info(attrs, lo, vis, info);
195 if self.is_union_item() {
198 let info = self.parse_item_union()?;
199 return self.mk_item_with_info(attrs, lo, vis, info);
202 if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? {
203 return Ok(Some(macro_def));
206 // Verify whether we have encountered a struct or method definition where the user forgot to
207 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
208 if vis.node.is_pub() && self.check_ident() && self.look_ahead(1, |t| *t != token::Not) {
209 // Space between `pub` keyword and the identifier
212 // ^^^ `sp` points here
213 let sp = self.prev_span.between(self.token.span);
214 let full_sp = self.prev_span.to(self.token.span);
215 let ident_sp = self.token.span;
216 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
217 // possible public struct definition where `struct` was forgotten
218 let ident = self.parse_ident().unwrap();
219 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
220 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
221 err.span_suggestion_short(
225 Applicability::MaybeIncorrect, // speculative
228 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
229 let ident = self.parse_ident().unwrap();
231 let kw_name = self.recover_first_param();
232 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
233 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
234 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
236 ("fn", kw_name, false)
237 } else if self.check(&token::OpenDelim(token::Brace)) {
239 ("fn", kw_name, false)
240 } else if self.check(&token::Colon) {
244 ("fn` or `struct", "function or struct", true)
247 let msg = format!("missing `{}` for {} definition", kw, kw_name);
248 let mut err = self.struct_span_err(sp, &msg);
250 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
252 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
253 err.span_suggestion_short(
257 Applicability::MachineApplicable,
260 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
263 "if you meant to call a macro, try",
264 format!("{}!", snippet),
265 // this is the `ambiguous` conditional branch
266 Applicability::MaybeIncorrect,
270 "if you meant to call a macro, remove the `pub` \
271 and add a trailing `!` after the identifier",
276 } else if self.look_ahead(1, |t| *t == token::Lt) {
277 let ident = self.parse_ident().unwrap();
278 self.eat_to_tokens(&[&token::Gt]);
280 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
281 ("fn", self.recover_first_param(), false)
282 } else if self.check(&token::OpenDelim(token::Brace)) {
283 ("struct", "struct", false)
285 ("fn` or `struct", "function or struct", true)
287 let msg = format!("missing `{}` for {} definition", kw, kw_name);
288 let mut err = self.struct_span_err(sp, &msg);
290 err.span_suggestion_short(
292 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
294 Applicability::MachineApplicable,
300 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis)
303 pub(super) fn mk_item_with_info(
305 attrs: Vec<Attribute>,
309 ) -> PResult<'a, Option<P<Item>>> {
310 let (ident, item, extra_attrs) = info;
311 let span = lo.to(self.prev_span);
312 let attrs = Self::maybe_append(attrs, extra_attrs);
313 Ok(Some(self.mk_item(span, ident, item, vis, attrs)))
316 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
317 if let Some(ref mut rhs) = rhs {
323 /// This is the fall-through for parsing items.
324 fn parse_macro_use_or_failure(
326 attrs: Vec<Attribute>,
327 macros_allowed: bool,
328 attributes_allowed: bool,
330 visibility: Visibility,
331 ) -> PResult<'a, Option<P<Item>>> {
333 && self.token.is_path_start()
334 && !(self.is_async_fn() && self.token.span.rust_2015())
336 // MACRO INVOCATION ITEM
338 let prev_span = self.prev_span;
339 self.complain_if_pub_macro(&visibility.node, prev_span);
342 let path = self.parse_path(PathStyle::Mod)?;
343 self.expect(&token::Not)?;
344 let args = self.parse_mac_args()?;
345 if args.need_semicolon() && !self.eat(&token::Semi) {
346 self.report_invalid_macro_expansion_item();
349 let hi = self.prev_span;
350 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
352 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
353 return Ok(Some(item));
356 // FAILURE TO PARSE ITEM
357 match visibility.node {
358 VisibilityKind::Inherited => {}
359 _ => return Err(self.struct_span_err(self.prev_span, "unmatched visibility `pub`")),
362 if !attributes_allowed && !attrs.is_empty() {
363 self.expected_item_err(&attrs)?;
368 /// Emits an expected-item-after-attributes error.
369 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
370 let message = match attrs.last() {
371 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
372 "expected item after doc comment"
374 _ => "expected item after attributes",
377 let mut err = self.struct_span_err(self.prev_span, message);
378 if attrs.last().unwrap().is_doc_comment() {
379 err.span_label(self.prev_span, "this doc comment doesn't document anything");
384 pub(super) fn is_async_fn(&self) -> bool {
385 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
388 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
389 fn parse_assoc_macro_invoc(
392 vis: Option<&Visibility>,
394 ) -> PResult<'a, Option<Mac>> {
395 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
396 let prev_span = self.prev_span;
397 let path = self.parse_path(PathStyle::Mod)?;
399 if path.segments.len() == 1 {
400 if !self.eat(&token::Not) {
401 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
404 self.expect(&token::Not)?;
407 if let Some(vis) = vis {
408 self.complain_if_pub_macro(&vis.node, prev_span);
413 // eat a matched-delimiter token tree:
414 let args = self.parse_mac_args()?;
415 if args.need_semicolon() {
419 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
425 fn missing_assoc_item_kind_err(
429 ) -> DiagnosticBuilder<'a> {
430 let expected_kinds = if item_type == "extern" {
431 "missing `fn`, `type`, or `static`"
433 "missing `fn`, `type`, or `const`"
436 // Given this code `path(`, it seems like this is not
437 // setting the visibility of a macro invocation, but rather
438 // a mistyped method declaration.
439 // Create a diagnostic pointing out that `fn` is missing.
441 // x | pub path(&self) {
442 // | ^ missing `fn`, `type`, or `const`
444 // ^^ `sp` below will point to this
445 let sp = prev_span.between(self.prev_span);
447 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
448 err.span_label(sp, expected_kinds);
452 /// Parses an implementation item, `impl` keyword is already parsed.
454 /// impl<'a, T> TYPE { /* impl items */ }
455 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
456 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
457 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
459 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
460 /// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
461 /// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
465 defaultness: Defaultness,
466 ) -> PResult<'a, ItemInfo> {
467 // First, parse generic parameters if necessary.
468 let mut generics = if self.choose_generics_over_qpath() {
469 self.parse_generics()?
471 let mut generics = Generics::default();
473 // /\ this is where `generics.span` should point when there are no type params.
474 generics.span = self.prev_span.shrink_to_hi();
478 let constness = self.parse_constness();
479 if let Const::Yes(span) = constness {
480 self.sess.gated_spans.gate(sym::const_trait_impl, span);
483 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
484 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
486 ast::ImplPolarity::Negative
488 ast::ImplPolarity::Positive
491 // Parse both types and traits as a type, then reinterpret if necessary.
492 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
493 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
495 let span = self.prev_span.between(self.token.span);
496 self.struct_span_err(span, "missing trait in a trait impl").emit();
497 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
502 // If `for` is missing we try to recover.
503 let has_for = self.eat_keyword(kw::For);
504 let missing_for_span = self.prev_span.between(self.token.span);
506 let ty_second = if self.token == token::DotDot {
507 // We need to report this error after `cfg` expansion for compatibility reasons
508 self.bump(); // `..`, do not add it to expected tokens
509 Some(self.mk_ty(self.prev_span, TyKind::Err))
510 } else if has_for || self.token.can_begin_type() {
511 Some(self.parse_ty()?)
516 generics.where_clause = self.parse_where_clause()?;
518 let (impl_items, attrs) = self.parse_impl_body()?;
520 let item_kind = match ty_second {
522 // impl Trait for Type
524 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
525 .span_suggestion_short(
529 Applicability::MachineApplicable,
534 let ty_first = ty_first.into_inner();
535 let path = match ty_first.kind {
536 // This notably includes paths passed through `ty` macro fragments (#46438).
537 TyKind::Path(None, path) => path,
539 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
540 err_path(ty_first.span)
543 let trait_ref = TraitRef { path, ref_id: ty_first.id };
551 of_trait: Some(trait_ref),
571 Ok((Ident::invalid(), item_kind, Some(attrs)))
574 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<P<AssocItem>>, Vec<Attribute>)> {
575 self.expect(&token::OpenDelim(token::Brace))?;
576 let attrs = self.parse_inner_attributes()?;
578 let mut impl_items = Vec::new();
579 while !self.eat(&token::CloseDelim(token::Brace)) {
580 let mut at_end = false;
581 match self.parse_impl_item(&mut at_end) {
582 Ok(impl_item) => impl_items.push(impl_item),
586 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
592 Ok((impl_items, attrs))
595 /// Parses defaultness (i.e., `default` or nothing).
596 fn parse_defaultness(&mut self) -> Defaultness {
597 // `pub` is included for better error messages
598 if self.check_keyword(kw::Default)
599 && self.is_keyword_ahead(
613 self.bump(); // `default`
620 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
621 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafe) -> PResult<'a, ItemInfo> {
622 // Parse optional `auto` prefix.
623 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
625 self.expect_keyword(kw::Trait)?;
626 let ident = self.parse_ident()?;
627 let mut tps = self.parse_generics()?;
629 // Parse optional colon and supertrait bounds.
630 let had_colon = self.eat(&token::Colon);
631 let span_at_colon = self.prev_span;
633 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
635 let span_before_eq = self.prev_span;
636 if self.eat(&token::Eq) {
637 // It's a trait alias.
639 let span = span_at_colon.to(span_before_eq);
640 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
643 let bounds = self.parse_generic_bounds(None)?;
644 tps.where_clause = self.parse_where_clause()?;
647 let whole_span = lo.to(self.prev_span);
648 if is_auto == IsAuto::Yes {
649 let msg = "trait aliases cannot be `auto`";
650 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
652 if let Unsafe::Yes(_) = unsafety {
653 let msg = "trait aliases cannot be `unsafe`";
654 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
657 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
659 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
661 // It's a normal trait.
662 tps.where_clause = self.parse_where_clause()?;
663 self.expect(&token::OpenDelim(token::Brace))?;
664 let mut trait_items = vec![];
665 while !self.eat(&token::CloseDelim(token::Brace)) {
666 if let token::DocComment(_) = self.token.kind {
667 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
672 "found a documentation comment that doesn't document anything",
675 "doc comments must come before what they document, maybe a \
676 comment was intended with `//`?",
683 let mut at_end = false;
684 match self.parse_trait_item(&mut at_end) {
685 Ok(item) => trait_items.push(item),
689 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
695 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
699 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
700 maybe_whole!(self, NtImplItem, |x| x);
701 self.parse_assoc_item(at_end, |_| true)
704 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
705 maybe_whole!(self, NtTraitItem, |x| x);
706 // This is somewhat dubious; We don't want to allow
707 // param names to be left off if there is a definition...
709 // We don't allow param names to be left off in edition 2018.
710 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
713 /// Parses associated items.
717 req_name: fn(&token::Token) -> bool,
718 ) -> PResult<'a, P<AssocItem>> {
719 let attrs = self.parse_outer_attributes()?;
720 let mut unclosed_delims = vec![];
721 let (mut item, tokens) = self.collect_tokens(|this| {
722 let item = this.parse_assoc_item_(at_end, attrs, req_name);
723 unclosed_delims.append(&mut this.unclosed_delims);
726 self.unclosed_delims.append(&mut unclosed_delims);
727 // See `parse_item` for why this clause is here.
728 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
729 item.tokens = Some(tokens);
734 fn parse_assoc_item_(
737 mut attrs: Vec<Attribute>,
738 req_name: fn(&token::Token) -> bool,
739 ) -> PResult<'a, AssocItem> {
740 let lo = self.token.span;
741 let vis = self.parse_visibility(FollowedByType::No)?;
742 let defaultness = self.parse_defaultness();
743 let (name, kind, generics) = if self.eat_keyword(kw::Type) {
744 self.parse_assoc_ty()?
745 } else if self.check_fn_front_matter() {
746 let (ident, sig, generics, body) = self.parse_fn(at_end, &mut attrs, req_name)?;
747 (ident, AssocItemKind::Fn(sig, body), generics)
748 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
749 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
751 self.parse_assoc_const()?
756 span: lo.to(self.prev_span),
767 /// This parses the grammar:
769 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
770 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
771 self.expect_keyword(kw::Const)?;
772 let ident = self.parse_ident()?;
773 self.expect(&token::Colon)?;
774 let ty = self.parse_ty()?;
775 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
777 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
780 /// Parses the following grammar:
782 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
783 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
784 let ident = self.parse_ident()?;
785 let mut generics = self.parse_generics()?;
787 // Parse optional colon and param bounds.
789 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
790 generics.where_clause = self.parse_where_clause()?;
792 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
795 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
798 /// Parses a `UseTree`.
801 /// USE_TREE = [`::`] `*` |
802 /// [`::`] `{` USE_TREE_LIST `}` |
804 /// PATH `::` `{` USE_TREE_LIST `}` |
805 /// PATH [`as` IDENT]
807 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
808 let lo = self.token.span;
810 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
811 let kind = if self.check(&token::OpenDelim(token::Brace))
812 || self.check(&token::BinOp(token::Star))
813 || self.is_import_coupler()
815 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
816 let mod_sep_ctxt = self.token.span.ctxt();
817 if self.eat(&token::ModSep) {
820 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
823 self.parse_use_tree_glob_or_nested()?
825 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
826 prefix = self.parse_path(PathStyle::Mod)?;
828 if self.eat(&token::ModSep) {
829 self.parse_use_tree_glob_or_nested()?
831 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
835 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
838 /// Parses `*` or `{...}`.
839 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
840 Ok(if self.eat(&token::BinOp(token::Star)) {
843 UseTreeKind::Nested(self.parse_use_tree_list()?)
847 /// Parses a `UseTreeKind::Nested(list)`.
850 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
852 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
853 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
857 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
858 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
861 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
862 match self.token.kind {
863 token::Ident(name, false) if name == kw::Underscore => {
864 let span = self.token.span;
866 Ok(Ident::new(name, span))
868 _ => self.parse_ident(),
872 /// Parses `extern crate` links.
877 /// extern crate foo;
878 /// extern crate bar as foo;
880 fn parse_item_extern_crate(
883 visibility: Visibility,
884 attrs: Vec<Attribute>,
885 ) -> PResult<'a, P<Item>> {
886 // Accept `extern crate name-like-this` for better diagnostics
887 let orig_name = self.parse_crate_name_with_dashes()?;
888 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
889 (rename, Some(orig_name.name))
895 let span = lo.to(self.prev_span);
896 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
899 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
900 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
901 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
903 let mut ident = if self.token.is_keyword(kw::SelfLower) {
904 self.parse_path_segment_ident()
908 let mut idents = vec![];
909 let mut replacement = vec![];
910 let mut fixed_crate_name = false;
911 // Accept `extern crate name-like-this` for better diagnostics.
912 let dash = token::BinOp(token::BinOpToken::Minus);
913 if self.token == dash {
914 // Do not include `-` as part of the expected tokens list.
915 while self.eat(&dash) {
916 fixed_crate_name = true;
917 replacement.push((self.prev_span, "_".to_string()));
918 idents.push(self.parse_ident()?);
921 if fixed_crate_name {
922 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
923 let mut fixed_name = format!("{}", ident.name);
925 fixed_name.push_str(&format!("_{}", part.name));
927 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
929 self.struct_span_err(fixed_name_sp, error_msg)
930 .span_label(fixed_name_sp, "dash-separated idents are not valid")
931 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
937 /// Parses `extern` for foreign ABIs modules.
939 /// `extern` is expected to have been
940 /// consumed before calling this method.
944 /// ```ignore (only-for-syntax-highlight)
948 fn parse_item_foreign_mod(
952 visibility: Visibility,
953 mut attrs: Vec<Attribute>,
954 ) -> PResult<'a, P<Item>> {
955 self.expect(&token::OpenDelim(token::Brace))?;
957 attrs.extend(self.parse_inner_attributes()?);
959 let mut foreign_items = vec![];
960 while !self.eat(&token::CloseDelim(token::Brace)) {
961 foreign_items.push(self.parse_foreign_item()?);
964 let prev_span = self.prev_span;
965 let m = ast::ForeignMod { abi, items: foreign_items };
966 let invalid = Ident::invalid();
967 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
970 /// Parses a foreign item.
971 pub fn parse_foreign_item(&mut self) -> PResult<'a, P<ForeignItem>> {
972 maybe_whole!(self, NtForeignItem, |ni| ni);
974 let mut attrs = self.parse_outer_attributes()?;
975 let lo = self.token.span;
976 let vis = self.parse_visibility(FollowedByType::No)?;
978 if self.check_keyword(kw::Type) {
980 self.parse_item_foreign_type(vis, lo, attrs)
981 } else if self.check_fn_front_matter() {
982 // FOREIGN FUNCTION ITEM
983 let (ident, sig, generics, body) = self.parse_fn(&mut false, &mut attrs, |_| true)?;
984 let kind = ForeignItemKind::Fn(sig, generics, body);
985 let span = lo.to(self.prev_span);
986 Ok(P(ast::ForeignItem {
995 } else if self.is_static_global() {
996 // FOREIGN STATIC ITEM
997 self.bump(); // `static`
998 self.parse_item_foreign_static(vis, lo, attrs)
999 } else if self.token.is_keyword(kw::Const) {
1000 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
1001 self.bump(); // `const`
1002 self.struct_span_err(self.prev_span, "extern items cannot be `const`")
1005 "try using a static value",
1006 "static".to_owned(),
1007 Applicability::MachineApplicable,
1010 self.parse_item_foreign_static(vis, lo, attrs)
1011 } else if let Some(mac) = self.parse_assoc_macro_invoc("extern", Some(&vis), &mut false)? {
1012 let kind = ForeignItemKind::Macro(mac);
1013 let span = lo.to(self.prev_span);
1014 let ident = Ident::invalid();
1015 Ok(P(ForeignItem { ident, span, id: DUMMY_NODE_ID, attrs, vis, kind, tokens: None }))
1017 if !attrs.is_empty() {
1018 self.expected_item_err(&attrs)?;
1024 /// Parses a static item from a foreign module.
1025 /// Assumes that the `static` keyword is already parsed.
1026 fn parse_item_foreign_static(
1028 vis: ast::Visibility,
1030 attrs: Vec<Attribute>,
1031 ) -> PResult<'a, P<ForeignItem>> {
1032 let mutbl = self.parse_mutability();
1033 let ident = self.parse_ident()?;
1034 self.expect(&token::Colon)?;
1035 let ty = self.parse_ty()?;
1036 let hi = self.token.span;
1037 self.expect_semi()?;
1041 kind: ForeignItemKind::Static(ty, mutbl),
1049 /// Parses a type from a foreign module.
1050 fn parse_item_foreign_type(
1052 vis: ast::Visibility,
1054 attrs: Vec<Attribute>,
1055 ) -> PResult<'a, P<ForeignItem>> {
1056 self.expect_keyword(kw::Type)?;
1058 let ident = self.parse_ident()?;
1059 let hi = self.token.span;
1060 self.expect_semi()?;
1061 Ok(P(ast::ForeignItem {
1064 kind: ForeignItemKind::Ty,
1072 fn is_static_global(&mut self) -> bool {
1073 if self.check_keyword(kw::Static) {
1074 // Check if this could be a closure.
1075 !self.look_ahead(1, |token| {
1076 if token.is_keyword(kw::Move) {
1080 token::BinOp(token::Or) | token::OrOr => true,
1089 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1090 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1092 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1093 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1094 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1096 // Parse the type of a `const` or `static mut?` item.
1097 // That is, the `":" $ty` fragment.
1098 let ty = if self.token == token::Eq {
1099 self.recover_missing_const_type(id, m)
1101 // Not `=` so expect `":"" $ty` as usual.
1102 self.expect(&token::Colon)?;
1106 self.expect(&token::Eq)?;
1107 let e = self.parse_expr()?;
1108 self.expect_semi()?;
1109 let item = match m {
1110 Some(m) => ItemKind::Static(ty, m, e),
1111 None => ItemKind::Const(ty, e),
1113 Ok((id, item, None))
1116 /// We were supposed to parse `:` but instead, we're already at `=`.
1117 /// This means that the type is missing.
1118 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1119 // Construct the error and stash it away with the hope
1120 // that typeck will later enrich the error with a type.
1121 let kind = match m {
1122 Some(Mutability::Mut) => "static mut",
1123 Some(Mutability::Not) => "static",
1126 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1127 err.span_suggestion(
1129 "provide a type for the item",
1130 format!("{}: <type>", id),
1131 Applicability::HasPlaceholders,
1133 err.stash(id.span, StashKey::ItemNoType);
1135 // The user intended that the type be inferred,
1136 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1137 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1140 /// Parses the grammar:
1141 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1142 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1143 let ident = self.parse_ident()?;
1144 let mut tps = self.parse_generics()?;
1145 tps.where_clause = self.parse_where_clause()?;
1146 self.expect(&token::Eq)?;
1147 let ty = self.parse_ty()?;
1148 self.expect_semi()?;
1149 Ok((ident, ty, tps))
1152 /// Parses an enum declaration.
1153 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1154 let id = self.parse_ident()?;
1155 let mut generics = self.parse_generics()?;
1156 generics.where_clause = self.parse_where_clause()?;
1159 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1160 self.recover_stmt();
1164 let enum_definition =
1165 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1166 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1169 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1170 let variant_attrs = self.parse_outer_attributes()?;
1171 let vlo = self.token.span;
1173 let vis = self.parse_visibility(FollowedByType::No)?;
1174 if !self.recover_nested_adt_item(kw::Enum)? {
1177 let ident = self.parse_ident()?;
1179 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1180 // Parse a struct variant.
1181 let (fields, recovered) = self.parse_record_struct_body()?;
1182 VariantData::Struct(fields, recovered)
1183 } else if self.check(&token::OpenDelim(token::Paren)) {
1184 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1186 VariantData::Unit(DUMMY_NODE_ID)
1190 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1192 let vr = ast::Variant {
1196 attrs: variant_attrs,
1199 span: vlo.to(self.prev_span),
1200 is_placeholder: false,
1206 /// Parses `struct Foo { ... }`.
1207 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1208 let class_name = self.parse_ident()?;
1210 let mut generics = self.parse_generics()?;
1212 // There is a special case worth noting here, as reported in issue #17904.
1213 // If we are parsing a tuple struct it is the case that the where clause
1214 // should follow the field list. Like so:
1216 // struct Foo<T>(T) where T: Copy;
1218 // If we are parsing a normal record-style struct it is the case
1219 // that the where clause comes before the body, and after the generics.
1220 // So if we look ahead and see a brace or a where-clause we begin
1221 // parsing a record style struct.
1223 // Otherwise if we look ahead and see a paren we parse a tuple-style
1226 let vdata = if self.token.is_keyword(kw::Where) {
1227 generics.where_clause = self.parse_where_clause()?;
1228 if self.eat(&token::Semi) {
1229 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1230 VariantData::Unit(DUMMY_NODE_ID)
1232 // If we see: `struct Foo<T> where T: Copy { ... }`
1233 let (fields, recovered) = self.parse_record_struct_body()?;
1234 VariantData::Struct(fields, recovered)
1236 // No `where` so: `struct Foo<T>;`
1237 } else if self.eat(&token::Semi) {
1238 VariantData::Unit(DUMMY_NODE_ID)
1239 // Record-style struct definition
1240 } else if self.token == token::OpenDelim(token::Brace) {
1241 let (fields, recovered) = self.parse_record_struct_body()?;
1242 VariantData::Struct(fields, recovered)
1243 // Tuple-style struct definition with optional where-clause.
1244 } else if self.token == token::OpenDelim(token::Paren) {
1245 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1246 generics.where_clause = self.parse_where_clause()?;
1247 self.expect_semi()?;
1250 let token_str = super::token_descr(&self.token);
1252 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1255 let mut err = self.struct_span_err(self.token.span, msg);
1256 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1260 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1263 /// Parses `union Foo { ... }`.
1264 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1265 let class_name = self.parse_ident()?;
1267 let mut generics = self.parse_generics()?;
1269 let vdata = if self.token.is_keyword(kw::Where) {
1270 generics.where_clause = self.parse_where_clause()?;
1271 let (fields, recovered) = self.parse_record_struct_body()?;
1272 VariantData::Struct(fields, recovered)
1273 } else if self.token == token::OpenDelim(token::Brace) {
1274 let (fields, recovered) = self.parse_record_struct_body()?;
1275 VariantData::Struct(fields, recovered)
1277 let token_str = super::token_descr(&self.token);
1278 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1279 let mut err = self.struct_span_err(self.token.span, msg);
1280 err.span_label(self.token.span, "expected `where` or `{` after union name");
1284 Ok((class_name, ItemKind::Union(vdata, generics), None))
1287 pub(super) fn is_union_item(&self) -> bool {
1288 self.token.is_keyword(kw::Union)
1289 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1292 fn parse_record_struct_body(
1294 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1295 let mut fields = Vec::new();
1296 let mut recovered = false;
1297 if self.eat(&token::OpenDelim(token::Brace)) {
1298 while self.token != token::CloseDelim(token::Brace) {
1299 let field = self.parse_struct_decl_field().map_err(|e| {
1300 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1305 Ok(field) => fields.push(field),
1312 self.eat(&token::CloseDelim(token::Brace));
1314 let token_str = super::token_descr(&self.token);
1315 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1316 let mut err = self.struct_span_err(self.token.span, msg);
1317 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1321 Ok((fields, recovered))
1324 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1325 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1326 // Unit like structs are handled in parse_item_struct function
1327 self.parse_paren_comma_seq(|p| {
1328 let attrs = p.parse_outer_attributes()?;
1329 let lo = p.token.span;
1330 let vis = p.parse_visibility(FollowedByType::Yes)?;
1331 let ty = p.parse_ty()?;
1333 span: lo.to(ty.span),
1339 is_placeholder: false,
1345 /// Parses an element of a struct declaration.
1346 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1347 let attrs = self.parse_outer_attributes()?;
1348 let lo = self.token.span;
1349 let vis = self.parse_visibility(FollowedByType::No)?;
1350 self.parse_single_struct_field(lo, vis, attrs)
1353 /// Parses a structure field declaration.
1354 fn parse_single_struct_field(
1358 attrs: Vec<Attribute>,
1359 ) -> PResult<'a, StructField> {
1360 let mut seen_comma: bool = false;
1361 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1362 if self.token == token::Comma {
1365 match self.token.kind {
1369 token::CloseDelim(token::Brace) => {}
1370 token::DocComment(_) => {
1371 let previous_span = self.prev_span;
1372 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1373 self.bump(); // consume the doc comment
1374 let comma_after_doc_seen = self.eat(&token::Comma);
1375 // `seen_comma` is always false, because we are inside doc block
1376 // condition is here to make code more readable
1377 if seen_comma == false && comma_after_doc_seen == true {
1380 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1383 if seen_comma == false {
1384 let sp = self.sess.source_map().next_point(previous_span);
1385 err.span_suggestion(
1387 "missing comma here",
1389 Applicability::MachineApplicable,
1396 let sp = self.prev_span.shrink_to_hi();
1397 let mut err = self.struct_span_err(
1399 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1401 if self.token.is_ident() {
1402 // This is likely another field; emit the diagnostic and keep going
1403 err.span_suggestion(
1405 "try adding a comma",
1407 Applicability::MachineApplicable,
1418 /// Parses a structure field.
1419 fn parse_name_and_ty(
1423 attrs: Vec<Attribute>,
1424 ) -> PResult<'a, StructField> {
1425 let name = self.parse_ident()?;
1426 self.expect(&token::Colon)?;
1427 let ty = self.parse_ty()?;
1429 span: lo.to(self.prev_span),
1435 is_placeholder: false,
1439 pub(super) fn eat_macro_def(
1441 attrs: &[Attribute],
1444 ) -> PResult<'a, Option<P<Item>>> {
1445 let (ident, def) = if self.eat_keyword(kw::Macro) {
1446 let ident = self.parse_ident()?;
1447 let body = if self.check(&token::OpenDelim(token::Brace)) {
1448 self.parse_mac_args()?
1449 } else if self.check(&token::OpenDelim(token::Paren)) {
1450 let params = self.parse_token_tree();
1451 let pspan = params.span();
1452 let body = if self.check(&token::OpenDelim(token::Brace)) {
1453 self.parse_token_tree()
1455 return self.unexpected();
1457 let bspan = body.span();
1458 let tokens = TokenStream::new(vec![
1460 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1463 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1464 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1466 return self.unexpected();
1469 (ident, ast::MacroDef { body, legacy: false })
1470 } else if self.check_keyword(sym::macro_rules)
1471 && self.look_ahead(1, |t| *t == token::Not)
1472 && self.look_ahead(2, |t| t.is_ident())
1474 let prev_span = self.prev_span;
1475 self.complain_if_pub_macro(&vis.node, prev_span);
1479 let ident = self.parse_ident()?;
1480 let body = self.parse_mac_args()?;
1481 if body.need_semicolon() && !self.eat(&token::Semi) {
1482 self.report_invalid_macro_expansion_item();
1485 (ident, ast::MacroDef { body, legacy: true })
1490 let span = lo.to(self.prev_span);
1493 self.sess.gated_spans.gate(sym::decl_macro, span);
1496 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1499 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1501 VisibilityKind::Inherited => {}
1503 let mut err = if self.token.is_keyword(sym::macro_rules) {
1505 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1506 err.span_suggestion(
1508 "try exporting the macro",
1509 "#[macro_export]".to_owned(),
1510 Applicability::MaybeIncorrect, // speculative
1515 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1516 err.help("try adjusting the macro to put `pub` inside the invocation");
1524 fn report_invalid_macro_expansion_item(&self) {
1525 let has_close_delim = self
1528 .span_to_snippet(self.prev_span)
1529 .map(|s| s.ends_with(")") || s.ends_with("]"))
1532 let mut err = self.struct_span_err(
1534 "macros that expand to items must be delimited with braces or followed by a semicolon",
1537 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1538 if has_close_delim {
1539 err.multipart_suggestion(
1540 "change the delimiters to curly braces",
1542 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1543 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1545 Applicability::MaybeIncorrect,
1548 err.span_suggestion(
1550 "change the delimiters to curly braces",
1551 " { /* items */ }".to_string(),
1552 Applicability::HasPlaceholders,
1556 err.span_suggestion(
1557 self.prev_span.shrink_to_hi(),
1560 Applicability::MaybeIncorrect,
1565 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1566 /// it is, we try to parse the item and report error about nested types.
1567 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1568 if (self.token.is_keyword(kw::Enum)
1569 || self.token.is_keyword(kw::Struct)
1570 || self.token.is_keyword(kw::Union))
1571 && self.look_ahead(1, |t| t.is_ident())
1573 let kw_token = self.token.clone();
1574 let kw_str = pprust::token_to_string(&kw_token);
1575 let item = self.parse_item()?;
1577 self.struct_span_err(
1579 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1583 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1585 Applicability::MaybeIncorrect,
1588 // We successfully parsed the item but we must inform the caller about nested problem.
1600 attrs: Vec<Attribute>,
1602 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1606 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1608 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1609 type ReqName = fn(&token::Token) -> bool;
1611 /// Parsing of functions and methods.
1612 impl<'a> Parser<'a> {
1613 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1617 attrs: &mut Vec<Attribute>,
1619 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1620 let header = self.parse_fn_front_matter()?; // `const ... fn`
1621 let ident = self.parse_ident()?; // `foo`
1622 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1623 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1624 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1625 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1626 Ok((ident, FnSig { header, decl }, generics, body))
1629 /// Parse the "body" of a function.
1630 /// This can either be `;` when there's no body,
1631 /// or e.g. a block when the function is a provided one.
1635 attrs: &mut Vec<Attribute>,
1636 ) -> PResult<'a, Option<P<Block>>> {
1637 let (inner_attrs, body) = match self.token.kind {
1642 token::OpenDelim(token::Brace) => {
1643 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1646 token::Interpolated(ref nt) => match **nt {
1647 token::NtBlock(..) => {
1648 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1651 _ => return self.expected_semi_or_open_brace(),
1653 _ => return self.expected_semi_or_open_brace(),
1655 attrs.extend(inner_attrs);
1660 /// Is the current token the start of an `FnHeader` / not a valid parse?
1661 fn check_fn_front_matter(&mut self) -> bool {
1662 // We use an over-approximation here.
1663 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1664 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1665 self.check_keyword(kw::Fn) // Definitely an `fn`.
1666 // `$qual fn` or `$qual $qual`:
1667 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1668 && self.look_ahead(1, |t| {
1669 // ...qualified and then `fn`, e.g. `const fn`.
1670 t.is_keyword(kw::Fn)
1671 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1672 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1675 || self.check_keyword(kw::Extern)
1676 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1677 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1680 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1681 /// up to and including the `fn` keyword. The formal grammar is:
1684 /// Extern = "extern" StringLit ;
1685 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1686 /// FnFrontMatter = FnQual? "fn" ;
1688 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1689 let constness = self.parse_constness();
1690 let asyncness = self.parse_asyncness();
1691 let unsafety = self.parse_unsafety();
1692 let ext = self.parse_extern()?;
1694 if let Async::Yes { span, .. } = asyncness {
1695 self.ban_async_in_2015(span);
1698 if !self.eat_keyword(kw::Fn) {
1699 // It is possible for `expect_one_of` to recover given the contents of
1700 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1701 // account for this.
1702 if !self.expect_one_of(&[], &[])? {
1707 Ok(FnHeader { constness, unsafety, asyncness, ext })
1710 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1711 fn ban_async_in_2015(&self, span: Span) {
1712 if span.rust_2015() {
1713 let diag = self.diagnostic();
1714 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1715 .note("to use `async fn`, switch to Rust 2018")
1716 .help("set `edition = \"2018\"` in `Cargo.toml`")
1717 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1722 /// Parses the parameter list and result type of a function declaration.
1723 pub(super) fn parse_fn_decl(
1726 ret_allow_plus: AllowPlus,
1727 ) -> PResult<'a, P<FnDecl>> {
1729 inputs: self.parse_fn_params(req_name)?,
1730 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1734 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1735 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1736 let mut first_param = true;
1737 // Parse the arguments, starting out with `self` being allowed...
1738 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1739 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1741 let lo = p.prev_span;
1742 // Skip every token until next possible arg or end.
1743 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1744 // Create a placeholder argument for proper arg count (issue #34264).
1745 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1747 // ...now that we've parsed the first argument, `self` is no longer allowed.
1748 first_param = false;
1751 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1752 self.deduplicate_recovered_params_names(&mut params);
1756 /// Parses a single function parameter.
1758 /// - `self` is syntactically allowed when `first_param` holds.
1759 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1760 let lo = self.token.span;
1761 let attrs = self.parse_outer_attributes()?;
1763 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1764 if let Some(mut param) = self.parse_self_param()? {
1765 param.attrs = attrs.into();
1766 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1769 let is_name_required = match self.token.kind {
1770 token::DotDotDot => false,
1771 _ => req_name(&self.token),
1773 let (pat, ty) = if is_name_required || self.is_named_param() {
1774 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1776 let pat = self.parse_fn_param_pat()?;
1777 if let Err(mut err) = self.expect(&token::Colon) {
1778 return if let Some(ident) =
1779 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1782 Ok(dummy_arg(ident))
1788 self.eat_incorrect_doc_comment_for_param_type();
1789 (pat, self.parse_ty_for_param()?)
1791 debug!("parse_param_general ident_to_pat");
1792 let parser_snapshot_before_ty = self.clone();
1793 self.eat_incorrect_doc_comment_for_param_type();
1794 let mut ty = self.parse_ty_for_param();
1796 && self.token != token::Comma
1797 && self.token != token::CloseDelim(token::Paren)
1799 // This wasn't actually a type, but a pattern looking like a type,
1800 // so we are going to rollback and re-parse for recovery.
1801 ty = self.unexpected();
1805 let ident = Ident::new(kw::Invalid, self.prev_span);
1806 let bm = BindingMode::ByValue(Mutability::Not);
1807 let pat = self.mk_pat_ident(ty.span, bm, ident);
1810 // If this is a C-variadic argument and we hit an error, return the error.
1811 Err(err) if self.token == token::DotDotDot => return Err(err),
1812 // Recover from attempting to parse the argument as a type without pattern.
1815 mem::replace(self, parser_snapshot_before_ty);
1816 self.recover_arg_parse()?
1821 let span = lo.to(self.token.span);
1824 attrs: attrs.into(),
1825 id: ast::DUMMY_NODE_ID,
1826 is_placeholder: false,
1833 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1834 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1835 // Extract an identifier *after* having confirmed that the token is one.
1836 let expect_self_ident = |this: &mut Self| {
1837 match this.token.kind {
1838 // Preserve hygienic context.
1839 token::Ident(name, _) => {
1840 let span = this.token.span;
1842 Ident::new(name, span)
1844 _ => unreachable!(),
1847 // Is `self` `n` tokens ahead?
1848 let is_isolated_self = |this: &Self, n| {
1849 this.is_keyword_ahead(n, &[kw::SelfLower])
1850 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1852 // Is `mut self` `n` tokens ahead?
1853 let is_isolated_mut_self =
1854 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1855 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1856 let parse_self_possibly_typed = |this: &mut Self, m| {
1857 let eself_ident = expect_self_ident(this);
1858 let eself_hi = this.prev_span;
1859 let eself = if this.eat(&token::Colon) {
1860 SelfKind::Explicit(this.parse_ty()?, m)
1864 Ok((eself, eself_ident, eself_hi))
1866 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1867 let recover_self_ptr = |this: &mut Self| {
1868 let msg = "cannot pass `self` by raw pointer";
1869 let span = this.token.span;
1870 this.struct_span_err(span, msg).span_label(span, msg).emit();
1872 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1875 // Parse optional `self` parameter of a method.
1876 // Only a limited set of initial token sequences is considered `self` parameters; anything
1877 // else is parsed as a normal function parameter list, so some lookahead is required.
1878 let eself_lo = self.token.span;
1879 let (eself, eself_ident, eself_hi) = match self.token.kind {
1880 token::BinOp(token::And) => {
1881 let eself = if is_isolated_self(self, 1) {
1884 SelfKind::Region(None, Mutability::Not)
1885 } else if is_isolated_mut_self(self, 1) {
1889 SelfKind::Region(None, Mutability::Mut)
1890 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1893 let lt = self.expect_lifetime();
1894 SelfKind::Region(Some(lt), Mutability::Not)
1895 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1898 let lt = self.expect_lifetime();
1900 SelfKind::Region(Some(lt), Mutability::Mut)
1905 (eself, expect_self_ident(self), self.prev_span)
1908 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1910 recover_self_ptr(self)?
1912 // `*mut self` and `*const self`
1913 token::BinOp(token::Star)
1914 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1918 recover_self_ptr(self)?
1920 // `self` and `self: TYPE`
1921 token::Ident(..) if is_isolated_self(self, 0) => {
1922 parse_self_possibly_typed(self, Mutability::Not)?
1924 // `mut self` and `mut self: TYPE`
1925 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1927 parse_self_possibly_typed(self, Mutability::Mut)?
1929 _ => return Ok(None),
1932 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1933 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1936 fn is_named_param(&self) -> bool {
1937 let offset = match self.token.kind {
1938 token::Interpolated(ref nt) => match **nt {
1939 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1942 token::BinOp(token::And) | token::AndAnd => 1,
1943 _ if self.token.is_keyword(kw::Mut) => 1,
1947 self.look_ahead(offset, |t| t.is_ident())
1948 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1951 fn recover_first_param(&mut self) -> &'static str {
1953 .parse_outer_attributes()
1954 .and_then(|_| self.parse_self_param())
1955 .map_err(|mut e| e.cancel())
1957 Ok(Some(_)) => "method",