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, 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;
86 let vis = self.parse_visibility(FollowedByType::No)?;
88 if let Some(info) = self.parse_item_kind(&mut attrs, macros_allowed, lo, &vis)? {
89 return Ok(Some(self.mk_item_with_info(attrs, lo, vis, info)));
92 // FAILURE TO PARSE ITEM
94 VisibilityKind::Inherited => {}
96 self.struct_span_err(vis.span, "unmatched visibility `pub`")
97 .span_label(vis.span, "the unmatched visibility")
98 .help("you likely meant to define an item, e.g., `pub fn foo() {}`")
103 if !attributes_allowed && !attrs.is_empty() {
104 self.expected_item_err(&attrs)?;
109 /// Parses one of the items allowed by the flags.
112 attrs: &mut Vec<Attribute>,
113 macros_allowed: bool,
116 ) -> PResult<'a, Option<ItemInfo>> {
117 let info = if self.eat_keyword(kw::Use) {
119 let tree = self.parse_use_tree()?;
121 (Ident::invalid(), ItemKind::Use(P(tree)), None)
122 } else if self.check_fn_front_matter() {
124 let (ident, sig, generics, body) = self.parse_fn(&mut false, attrs, |_| true)?;
125 (ident, ItemKind::Fn(sig, generics, body), None)
126 } else if self.eat_keyword(kw::Extern) {
127 if self.eat_keyword(kw::Crate) {
129 self.parse_item_extern_crate()?
132 self.parse_item_foreign_mod()?
134 } else if self.is_static_global() {
136 self.bump(); // `static`
137 let m = self.parse_mutability();
138 self.parse_item_const(Some(m))?
139 } else if let Const::Yes(const_span) = self.parse_constness() {
141 if self.eat_keyword(kw::Mut) {
142 let prev_span = self.prev_span;
143 self.struct_span_err(prev_span, "const globals cannot be mutable")
144 .span_label(prev_span, "cannot be mutable")
147 "you might want to declare a static instead",
149 Applicability::MaybeIncorrect,
154 self.parse_item_const(None)?
155 } else if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
158 let unsafety = self.parse_unsafety();
159 self.parse_item_trait(lo, unsafety)?
160 } else if self.check_keyword(kw::Impl)
161 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
162 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
165 let defaultness = self.parse_defaultness();
166 let unsafety = self.parse_unsafety();
167 self.expect_keyword(kw::Impl)?;
168 self.parse_item_impl(unsafety, defaultness)?
169 } else if self.eat_keyword(kw::Mod) {
171 self.parse_item_mod(&attrs[..])?
172 } else if self.eat_keyword(kw::Type) {
174 let (ident, ty, generics) = self.parse_type_alias()?;
175 (ident, ItemKind::TyAlias(ty, generics), None)
176 } else if self.eat_keyword(kw::Enum) {
178 self.parse_item_enum()?
179 } else if self.check_keyword(kw::Trait)
180 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
183 self.parse_item_trait(lo, Unsafe::No)?
184 } else if self.eat_keyword(kw::Struct) {
186 self.parse_item_struct()?
187 } else if self.is_union_item() {
189 self.bump(); // `union`
190 self.parse_item_union()?
191 } else if self.eat_keyword(kw::Macro) {
193 self.parse_item_decl_macro(lo)?
194 } else if self.is_macro_rules_item() {
196 self.parse_item_macro_rules(vis)?
197 } else if vis.node.is_pub()
198 && self.check_ident()
199 && self.look_ahead(1, |t| *t != token::Not)
201 self.recover_missing_kw_before_item()?;
203 } else if macros_allowed && self.token.is_path_start() {
204 // MACRO INVOCATION ITEM
205 self.parse_item_macro(vis)?
212 /// Recover on encountering a struct or method definition where the user
213 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
214 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
215 // Space between `pub` keyword and the identifier
218 // ^^^ `sp` points here
219 let sp = self.prev_span.between(self.token.span);
220 let full_sp = self.prev_span.to(self.token.span);
221 let ident_sp = self.token.span;
222 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
223 // possible public struct definition where `struct` was forgotten
224 let ident = self.parse_ident().unwrap();
225 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
226 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
227 err.span_suggestion_short(
231 Applicability::MaybeIncorrect, // speculative
234 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
235 let ident = self.parse_ident().unwrap();
237 let kw_name = self.recover_first_param();
238 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
239 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
240 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
242 ("fn", kw_name, false)
243 } else if self.check(&token::OpenDelim(token::Brace)) {
245 ("fn", kw_name, false)
246 } else if self.check(&token::Colon) {
250 ("fn` or `struct", "function or struct", true)
253 let msg = format!("missing `{}` for {} definition", kw, kw_name);
254 let mut err = self.struct_span_err(sp, &msg);
256 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
258 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
259 err.span_suggestion_short(
263 Applicability::MachineApplicable,
266 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
269 "if you meant to call a macro, try",
270 format!("{}!", snippet),
271 // this is the `ambiguous` conditional branch
272 Applicability::MaybeIncorrect,
276 "if you meant to call a macro, remove the `pub` \
277 and add a trailing `!` after the identifier",
282 } else if self.look_ahead(1, |t| *t == token::Lt) {
283 let ident = self.parse_ident().unwrap();
284 self.eat_to_tokens(&[&token::Gt]);
286 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
287 ("fn", self.recover_first_param(), false)
288 } else if self.check(&token::OpenDelim(token::Brace)) {
289 ("struct", "struct", false)
291 ("fn` or `struct", "function or struct", true)
293 let msg = format!("missing `{}` for {} definition", kw, kw_name);
294 let mut err = self.struct_span_err(sp, &msg);
296 err.span_suggestion_short(
298 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
300 Applicability::MachineApplicable,
309 pub(super) fn mk_item_with_info(
311 attrs: Vec<Attribute>,
316 let (ident, item, extra_attrs) = info;
317 let span = lo.to(self.prev_span);
318 let attrs = Self::maybe_append(attrs, extra_attrs);
319 self.mk_item(span, ident, item, vis, attrs)
322 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
323 if let Some(ref mut rhs) = rhs {
329 /// Parses an item macro, e.g., `item!();`.
330 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
331 self.complain_if_pub_macro(&vis.node, vis.span);
334 let path = self.parse_path(PathStyle::Mod)?;
335 self.expect(&token::Not)?;
336 let args = self.parse_mac_args()?;
337 if args.need_semicolon() && !self.eat(&token::Semi) {
338 self.report_invalid_macro_expansion_item();
341 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
342 Ok((Ident::invalid(), ItemKind::Mac(mac), None))
345 /// Emits an expected-item-after-attributes error.
346 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
347 let message = match attrs.last() {
348 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
349 "expected item after doc comment"
351 _ => "expected item after attributes",
354 let mut err = self.struct_span_err(self.prev_span, message);
355 if attrs.last().unwrap().is_doc_comment() {
356 err.span_label(self.prev_span, "this doc comment doesn't document anything");
361 pub(super) fn is_async_fn(&self) -> bool {
362 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
365 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
366 fn parse_assoc_macro_invoc(
369 vis: Option<&Visibility>,
371 ) -> PResult<'a, Option<Mac>> {
372 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
373 let prev_span = self.prev_span;
374 let path = self.parse_path(PathStyle::Mod)?;
376 if path.segments.len() == 1 {
377 if !self.eat(&token::Not) {
378 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
381 self.expect(&token::Not)?;
384 if let Some(vis) = vis {
385 self.complain_if_pub_macro(&vis.node, prev_span);
390 // eat a matched-delimiter token tree:
391 let args = self.parse_mac_args()?;
392 if args.need_semicolon() {
396 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
402 fn missing_assoc_item_kind_err(
406 ) -> DiagnosticBuilder<'a> {
407 let expected_kinds = if item_type == "extern" {
408 "missing `fn`, `type`, or `static`"
410 "missing `fn`, `type`, or `const`"
413 // Given this code `path(`, it seems like this is not
414 // setting the visibility of a macro invocation, but rather
415 // a mistyped method declaration.
416 // Create a diagnostic pointing out that `fn` is missing.
418 // x | pub path(&self) {
419 // | ^ missing `fn`, `type`, or `const`
421 // ^^ `sp` below will point to this
422 let sp = prev_span.between(self.prev_span);
424 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
425 err.span_label(sp, expected_kinds);
429 /// Parses an implementation item, `impl` keyword is already parsed.
431 /// impl<'a, T> TYPE { /* impl items */ }
432 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
433 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
434 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
436 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
437 /// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
438 /// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
442 defaultness: Defaultness,
443 ) -> PResult<'a, ItemInfo> {
444 // First, parse generic parameters if necessary.
445 let mut generics = if self.choose_generics_over_qpath() {
446 self.parse_generics()?
448 let mut generics = Generics::default();
450 // /\ this is where `generics.span` should point when there are no type params.
451 generics.span = self.prev_span.shrink_to_hi();
455 let constness = self.parse_constness();
456 if let Const::Yes(span) = constness {
457 self.sess.gated_spans.gate(sym::const_trait_impl, span);
460 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
461 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
463 ast::ImplPolarity::Negative
465 ast::ImplPolarity::Positive
468 // Parse both types and traits as a type, then reinterpret if necessary.
469 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
470 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
472 let span = self.prev_span.between(self.token.span);
473 self.struct_span_err(span, "missing trait in a trait impl").emit();
474 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
479 // If `for` is missing we try to recover.
480 let has_for = self.eat_keyword(kw::For);
481 let missing_for_span = self.prev_span.between(self.token.span);
483 let ty_second = if self.token == token::DotDot {
484 // We need to report this error after `cfg` expansion for compatibility reasons
485 self.bump(); // `..`, do not add it to expected tokens
486 Some(self.mk_ty(self.prev_span, TyKind::Err))
487 } else if has_for || self.token.can_begin_type() {
488 Some(self.parse_ty()?)
493 generics.where_clause = self.parse_where_clause()?;
495 let (impl_items, attrs) = self.parse_item_list(|p, at_end| p.parse_impl_item(at_end))?;
497 let item_kind = match ty_second {
499 // impl Trait for Type
501 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
502 .span_suggestion_short(
506 Applicability::MachineApplicable,
511 let ty_first = ty_first.into_inner();
512 let path = match ty_first.kind {
513 // This notably includes paths passed through `ty` macro fragments (#46438).
514 TyKind::Path(None, path) => path,
516 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
517 err_path(ty_first.span)
520 let trait_ref = TraitRef { path, ref_id: ty_first.id };
528 of_trait: Some(trait_ref),
548 Ok((Ident::invalid(), item_kind, Some(attrs)))
551 fn parse_item_list<T>(
553 mut parse_item: impl FnMut(&mut Parser<'a>, &mut bool) -> PResult<'a, T>,
554 ) -> PResult<'a, (Vec<T>, Vec<Attribute>)> {
555 self.expect(&token::OpenDelim(token::Brace))?;
556 let attrs = self.parse_inner_attributes()?;
558 let mut items = Vec::new();
559 while !self.eat(&token::CloseDelim(token::Brace)) {
560 if self.recover_doc_comment_before_brace() {
563 let mut at_end = false;
564 match parse_item(self, &mut at_end) {
565 Ok(item) => items.push(item),
569 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
578 /// Recover on a doc comment before `}`.
579 fn recover_doc_comment_before_brace(&mut self) -> bool {
580 if let token::DocComment(_) = self.token.kind {
581 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
586 "found a documentation comment that doesn't document anything",
588 .span_label(self.token.span, "this doc comment doesn't document anything")
590 "doc comments must come before what they document, maybe a \
591 comment was intended with `//`?",
601 /// Parses defaultness (i.e., `default` or nothing).
602 fn parse_defaultness(&mut self) -> Defaultness {
603 // `pub` is included for better error messages
604 if self.check_keyword(kw::Default)
605 && self.is_keyword_ahead(
619 self.bump(); // `default`
626 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
627 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafe) -> PResult<'a, ItemInfo> {
628 // Parse optional `auto` prefix.
629 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
631 self.expect_keyword(kw::Trait)?;
632 let ident = self.parse_ident()?;
633 let mut tps = self.parse_generics()?;
635 // Parse optional colon and supertrait bounds.
636 let had_colon = self.eat(&token::Colon);
637 let span_at_colon = self.prev_span;
639 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
641 let span_before_eq = self.prev_span;
642 if self.eat(&token::Eq) {
643 // It's a trait alias.
645 let span = span_at_colon.to(span_before_eq);
646 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
649 let bounds = self.parse_generic_bounds(None)?;
650 tps.where_clause = self.parse_where_clause()?;
653 let whole_span = lo.to(self.prev_span);
654 if is_auto == IsAuto::Yes {
655 let msg = "trait aliases cannot be `auto`";
656 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
658 if let Unsafe::Yes(_) = unsafety {
659 let msg = "trait aliases cannot be `unsafe`";
660 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
663 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
665 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
667 // It's a normal trait.
668 tps.where_clause = self.parse_where_clause()?;
669 let (items, attrs) = self.parse_item_list(|p, at_end| p.parse_trait_item(at_end))?;
670 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items), Some(attrs)))
674 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
675 maybe_whole!(self, NtImplItem, |x| x);
676 self.parse_assoc_item(at_end, |_| true)
679 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
680 maybe_whole!(self, NtTraitItem, |x| x);
681 // This is somewhat dubious; We don't want to allow
682 // param names to be left off if there is a definition...
684 // We don't allow param names to be left off in edition 2018.
685 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
688 /// Parses associated items.
692 req_name: fn(&token::Token) -> bool,
693 ) -> PResult<'a, P<AssocItem>> {
694 let attrs = self.parse_outer_attributes()?;
695 let mut unclosed_delims = vec![];
696 let (mut item, tokens) = self.collect_tokens(|this| {
697 let item = this.parse_assoc_item_(at_end, attrs, req_name);
698 unclosed_delims.append(&mut this.unclosed_delims);
701 self.unclosed_delims.append(&mut unclosed_delims);
702 // See `parse_item` for why this clause is here.
703 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
704 item.tokens = Some(tokens);
709 fn parse_assoc_item_(
712 mut attrs: Vec<Attribute>,
713 req_name: fn(&token::Token) -> bool,
714 ) -> PResult<'a, AssocItem> {
715 let lo = self.token.span;
716 let vis = self.parse_visibility(FollowedByType::No)?;
717 let defaultness = self.parse_defaultness();
719 let (ident, kind, generics) = if self.eat_keyword(kw::Type) {
720 self.parse_assoc_ty()?
721 } else if self.check_fn_front_matter() {
722 let (ident, sig, generics, body) = self.parse_fn(at_end, &mut attrs, req_name)?;
723 (ident, AssocItemKind::Fn(sig, body), generics)
724 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
725 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
727 self.parse_assoc_const()?
730 let span = lo.to(self.prev_span);
731 let id = DUMMY_NODE_ID;
732 Ok(AssocItem { id, span, ident, attrs, vis, defaultness, generics, kind, tokens: None })
735 /// This parses the grammar:
737 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
738 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
739 self.expect_keyword(kw::Const)?;
740 let ident = self.parse_ident()?;
741 self.expect(&token::Colon)?;
742 let ty = self.parse_ty()?;
743 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
745 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
748 /// Parses the following grammar:
750 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
751 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
752 let ident = self.parse_ident()?;
753 let mut generics = self.parse_generics()?;
755 // Parse optional colon and param bounds.
757 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
758 generics.where_clause = self.parse_where_clause()?;
760 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
763 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
766 /// Parses a `UseTree`.
769 /// USE_TREE = [`::`] `*` |
770 /// [`::`] `{` USE_TREE_LIST `}` |
772 /// PATH `::` `{` USE_TREE_LIST `}` |
773 /// PATH [`as` IDENT]
775 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
776 let lo = self.token.span;
778 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
779 let kind = if self.check(&token::OpenDelim(token::Brace))
780 || self.check(&token::BinOp(token::Star))
781 || self.is_import_coupler()
783 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
784 let mod_sep_ctxt = self.token.span.ctxt();
785 if self.eat(&token::ModSep) {
788 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
791 self.parse_use_tree_glob_or_nested()?
793 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
794 prefix = self.parse_path(PathStyle::Mod)?;
796 if self.eat(&token::ModSep) {
797 self.parse_use_tree_glob_or_nested()?
799 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
803 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
806 /// Parses `*` or `{...}`.
807 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
808 Ok(if self.eat(&token::BinOp(token::Star)) {
811 UseTreeKind::Nested(self.parse_use_tree_list()?)
815 /// Parses a `UseTreeKind::Nested(list)`.
818 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
820 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
821 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
825 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
826 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
829 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
830 match self.token.kind {
831 token::Ident(name, false) if name == kw::Underscore => {
832 let span = self.token.span;
834 Ok(Ident::new(name, span))
836 _ => self.parse_ident(),
840 /// Parses `extern crate` links.
845 /// extern crate foo;
846 /// extern crate bar as foo;
848 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
849 // Accept `extern crate name-like-this` for better diagnostics
850 let orig_name = self.parse_crate_name_with_dashes()?;
851 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
852 (rename, Some(orig_name.name))
857 Ok((item_name, ItemKind::ExternCrate(orig_name), None))
860 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
861 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
862 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
864 let mut ident = if self.token.is_keyword(kw::SelfLower) {
865 self.parse_path_segment_ident()
869 let mut idents = vec![];
870 let mut replacement = vec![];
871 let mut fixed_crate_name = false;
872 // Accept `extern crate name-like-this` for better diagnostics.
873 let dash = token::BinOp(token::BinOpToken::Minus);
874 if self.token == dash {
875 // Do not include `-` as part of the expected tokens list.
876 while self.eat(&dash) {
877 fixed_crate_name = true;
878 replacement.push((self.prev_span, "_".to_string()));
879 idents.push(self.parse_ident()?);
882 if fixed_crate_name {
883 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
884 let mut fixed_name = format!("{}", ident.name);
886 fixed_name.push_str(&format!("_{}", part.name));
888 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
890 self.struct_span_err(fixed_name_sp, error_msg)
891 .span_label(fixed_name_sp, "dash-separated idents are not valid")
892 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
898 /// Parses `extern` for foreign ABIs modules.
900 /// `extern` is expected to have been consumed before calling this method.
904 /// ```ignore (only-for-syntax-highlight)
908 fn parse_item_foreign_mod(&mut self) -> PResult<'a, ItemInfo> {
909 let abi = self.parse_abi(); // ABI?
910 let (items, attrs) = self.parse_item_list(|p, at_end| p.parse_foreign_item(at_end))?;
911 let module = ast::ForeignMod { abi, items };
912 Ok((Ident::invalid(), ItemKind::ForeignMod(module), Some(attrs)))
915 /// Parses a foreign item (one in an `extern { ... }` block).
916 pub fn parse_foreign_item(&mut self, at_end: &mut bool) -> PResult<'a, P<ForeignItem>> {
917 maybe_whole!(self, NtForeignItem, |ni| ni);
919 let mut attrs = self.parse_outer_attributes()?;
920 let lo = self.token.span;
921 let vis = self.parse_visibility(FollowedByType::No)?;
923 let (ident, kind) = if self.check_keyword(kw::Type) {
925 self.parse_item_foreign_type()?
926 } else if self.check_fn_front_matter() {
927 // FOREIGN FUNCTION ITEM
928 let (ident, sig, generics, body) = self.parse_fn(at_end, &mut attrs, |_| true)?;
929 (ident, ForeignItemKind::Fn(sig, generics, body))
930 } else if self.is_static_global() {
931 // FOREIGN STATIC ITEM
932 self.bump(); // `static`
933 self.parse_item_foreign_static()?
934 } else if self.token.is_keyword(kw::Const) {
935 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
936 self.bump(); // `const`
937 self.struct_span_err(self.prev_span, "extern items cannot be `const`")
940 "try using a static value",
942 Applicability::MachineApplicable,
945 self.parse_item_foreign_static()?
946 } else if let Some(mac) = self.parse_assoc_macro_invoc("extern", Some(&vis), at_end)? {
947 (Ident::invalid(), ForeignItemKind::Macro(mac))
949 if !attrs.is_empty() {
950 self.expected_item_err(&attrs)?;
955 let span = lo.to(self.prev_span);
956 Ok(P(ast::ForeignItem { ident, attrs, kind, id: DUMMY_NODE_ID, span, vis, tokens: None }))
959 /// Parses a static item from a foreign module.
960 /// Assumes that the `static` keyword is already parsed.
961 fn parse_item_foreign_static(&mut self) -> PResult<'a, (Ident, ForeignItemKind)> {
962 let mutbl = self.parse_mutability();
963 let ident = self.parse_ident()?;
964 self.expect(&token::Colon)?;
965 let ty = self.parse_ty()?;
967 Ok((ident, ForeignItemKind::Static(ty, mutbl)))
970 /// Parses a type from a foreign module.
971 fn parse_item_foreign_type(&mut self) -> PResult<'a, (Ident, ForeignItemKind)> {
972 self.expect_keyword(kw::Type)?;
973 let ident = self.parse_ident()?;
975 Ok((ident, ForeignItemKind::Ty))
978 fn is_static_global(&mut self) -> bool {
979 if self.check_keyword(kw::Static) {
980 // Check if this could be a closure.
981 !self.look_ahead(1, |token| {
982 if token.is_keyword(kw::Move) {
986 token::BinOp(token::Or) | token::OrOr => true,
995 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
996 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
998 /// When `m` is `"const"`, `$ident` may also be `"_"`.
999 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1000 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1002 // Parse the type of a `const` or `static mut?` item.
1003 // That is, the `":" $ty` fragment.
1004 let ty = if self.token == token::Eq {
1005 self.recover_missing_const_type(id, m)
1007 // Not `=` so expect `":"" $ty` as usual.
1008 self.expect(&token::Colon)?;
1012 self.expect(&token::Eq)?;
1013 let e = self.parse_expr()?;
1014 self.expect_semi()?;
1015 let item = match m {
1016 Some(m) => ItemKind::Static(ty, m, e),
1017 None => ItemKind::Const(ty, e),
1019 Ok((id, item, None))
1022 /// We were supposed to parse `:` but instead, we're already at `=`.
1023 /// This means that the type is missing.
1024 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1025 // Construct the error and stash it away with the hope
1026 // that typeck will later enrich the error with a type.
1027 let kind = match m {
1028 Some(Mutability::Mut) => "static mut",
1029 Some(Mutability::Not) => "static",
1032 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1033 err.span_suggestion(
1035 "provide a type for the item",
1036 format!("{}: <type>", id),
1037 Applicability::HasPlaceholders,
1039 err.stash(id.span, StashKey::ItemNoType);
1041 // The user intended that the type be inferred,
1042 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1043 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1046 /// Parses the grammar:
1047 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1048 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1049 let ident = self.parse_ident()?;
1050 let mut tps = self.parse_generics()?;
1051 tps.where_clause = self.parse_where_clause()?;
1052 self.expect(&token::Eq)?;
1053 let ty = self.parse_ty()?;
1054 self.expect_semi()?;
1055 Ok((ident, ty, tps))
1058 /// Parses an enum declaration.
1059 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1060 let id = self.parse_ident()?;
1061 let mut generics = self.parse_generics()?;
1062 generics.where_clause = self.parse_where_clause()?;
1065 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1066 self.recover_stmt();
1070 let enum_definition =
1071 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1072 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1075 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1076 let variant_attrs = self.parse_outer_attributes()?;
1077 let vlo = self.token.span;
1079 let vis = self.parse_visibility(FollowedByType::No)?;
1080 if !self.recover_nested_adt_item(kw::Enum)? {
1083 let ident = self.parse_ident()?;
1085 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1086 // Parse a struct variant.
1087 let (fields, recovered) = self.parse_record_struct_body()?;
1088 VariantData::Struct(fields, recovered)
1089 } else if self.check(&token::OpenDelim(token::Paren)) {
1090 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1092 VariantData::Unit(DUMMY_NODE_ID)
1096 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1098 let vr = ast::Variant {
1102 attrs: variant_attrs,
1105 span: vlo.to(self.prev_span),
1106 is_placeholder: false,
1112 /// Parses `struct Foo { ... }`.
1113 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1114 let class_name = self.parse_ident()?;
1116 let mut generics = self.parse_generics()?;
1118 // There is a special case worth noting here, as reported in issue #17904.
1119 // If we are parsing a tuple struct it is the case that the where clause
1120 // should follow the field list. Like so:
1122 // struct Foo<T>(T) where T: Copy;
1124 // If we are parsing a normal record-style struct it is the case
1125 // that the where clause comes before the body, and after the generics.
1126 // So if we look ahead and see a brace or a where-clause we begin
1127 // parsing a record style struct.
1129 // Otherwise if we look ahead and see a paren we parse a tuple-style
1132 let vdata = if self.token.is_keyword(kw::Where) {
1133 generics.where_clause = self.parse_where_clause()?;
1134 if self.eat(&token::Semi) {
1135 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1136 VariantData::Unit(DUMMY_NODE_ID)
1138 // If we see: `struct Foo<T> where T: Copy { ... }`
1139 let (fields, recovered) = self.parse_record_struct_body()?;
1140 VariantData::Struct(fields, recovered)
1142 // No `where` so: `struct Foo<T>;`
1143 } else if self.eat(&token::Semi) {
1144 VariantData::Unit(DUMMY_NODE_ID)
1145 // Record-style struct definition
1146 } else if self.token == token::OpenDelim(token::Brace) {
1147 let (fields, recovered) = self.parse_record_struct_body()?;
1148 VariantData::Struct(fields, recovered)
1149 // Tuple-style struct definition with optional where-clause.
1150 } else if self.token == token::OpenDelim(token::Paren) {
1151 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1152 generics.where_clause = self.parse_where_clause()?;
1153 self.expect_semi()?;
1156 let token_str = super::token_descr(&self.token);
1158 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1161 let mut err = self.struct_span_err(self.token.span, msg);
1162 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1166 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1169 /// Parses `union Foo { ... }`.
1170 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1171 let class_name = self.parse_ident()?;
1173 let mut generics = self.parse_generics()?;
1175 let vdata = if self.token.is_keyword(kw::Where) {
1176 generics.where_clause = self.parse_where_clause()?;
1177 let (fields, recovered) = self.parse_record_struct_body()?;
1178 VariantData::Struct(fields, recovered)
1179 } else if self.token == token::OpenDelim(token::Brace) {
1180 let (fields, recovered) = self.parse_record_struct_body()?;
1181 VariantData::Struct(fields, recovered)
1183 let token_str = super::token_descr(&self.token);
1184 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1185 let mut err = self.struct_span_err(self.token.span, msg);
1186 err.span_label(self.token.span, "expected `where` or `{` after union name");
1190 Ok((class_name, ItemKind::Union(vdata, generics), None))
1193 pub(super) fn is_union_item(&self) -> bool {
1194 self.token.is_keyword(kw::Union)
1195 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1198 fn parse_record_struct_body(
1200 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1201 let mut fields = Vec::new();
1202 let mut recovered = false;
1203 if self.eat(&token::OpenDelim(token::Brace)) {
1204 while self.token != token::CloseDelim(token::Brace) {
1205 let field = self.parse_struct_decl_field().map_err(|e| {
1206 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1211 Ok(field) => fields.push(field),
1218 self.eat(&token::CloseDelim(token::Brace));
1220 let token_str = super::token_descr(&self.token);
1221 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1222 let mut err = self.struct_span_err(self.token.span, msg);
1223 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1227 Ok((fields, recovered))
1230 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1231 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1232 // Unit like structs are handled in parse_item_struct function
1233 self.parse_paren_comma_seq(|p| {
1234 let attrs = p.parse_outer_attributes()?;
1235 let lo = p.token.span;
1236 let vis = p.parse_visibility(FollowedByType::Yes)?;
1237 let ty = p.parse_ty()?;
1239 span: lo.to(ty.span),
1245 is_placeholder: false,
1251 /// Parses an element of a struct declaration.
1252 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1253 let attrs = self.parse_outer_attributes()?;
1254 let lo = self.token.span;
1255 let vis = self.parse_visibility(FollowedByType::No)?;
1256 self.parse_single_struct_field(lo, vis, attrs)
1259 /// Parses a structure field declaration.
1260 fn parse_single_struct_field(
1264 attrs: Vec<Attribute>,
1265 ) -> PResult<'a, StructField> {
1266 let mut seen_comma: bool = false;
1267 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1268 if self.token == token::Comma {
1271 match self.token.kind {
1275 token::CloseDelim(token::Brace) => {}
1276 token::DocComment(_) => {
1277 let previous_span = self.prev_span;
1278 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1279 self.bump(); // consume the doc comment
1280 let comma_after_doc_seen = self.eat(&token::Comma);
1281 // `seen_comma` is always false, because we are inside doc block
1282 // condition is here to make code more readable
1283 if seen_comma == false && comma_after_doc_seen == true {
1286 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1289 if seen_comma == false {
1290 let sp = self.sess.source_map().next_point(previous_span);
1291 err.span_suggestion(
1293 "missing comma here",
1295 Applicability::MachineApplicable,
1302 let sp = self.prev_span.shrink_to_hi();
1303 let mut err = self.struct_span_err(
1305 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1307 if self.token.is_ident() {
1308 // This is likely another field; emit the diagnostic and keep going
1309 err.span_suggestion(
1311 "try adding a comma",
1313 Applicability::MachineApplicable,
1324 /// Parses a structure field.
1325 fn parse_name_and_ty(
1329 attrs: Vec<Attribute>,
1330 ) -> PResult<'a, StructField> {
1331 let name = self.parse_ident()?;
1332 self.expect(&token::Colon)?;
1333 let ty = self.parse_ty()?;
1335 span: lo.to(self.prev_span),
1341 is_placeholder: false,
1345 /// Parses a declarative macro 2.0 definition.
1346 /// The `macro` keyword has already been parsed.
1347 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1348 let ident = self.parse_ident()?;
1349 let body = if self.check(&token::OpenDelim(token::Brace)) {
1350 self.parse_mac_args()?
1351 } else if self.check(&token::OpenDelim(token::Paren)) {
1352 let params = self.parse_token_tree();
1353 let pspan = params.span();
1354 let body = if self.check(&token::OpenDelim(token::Brace)) {
1355 self.parse_token_tree()
1357 return self.unexpected();
1359 let bspan = body.span();
1360 let tokens = TokenStream::new(vec![
1362 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1365 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1366 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1368 return self.unexpected();
1371 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1372 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false }), None))
1375 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1376 fn is_macro_rules_item(&mut self) -> bool {
1377 self.check_keyword(sym::macro_rules)
1378 && self.look_ahead(1, |t| *t == token::Not)
1379 && self.look_ahead(2, |t| t.is_ident())
1382 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1383 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1384 self.complain_if_pub_macro(&vis.node, vis.span);
1385 self.expect_keyword(sym::macro_rules)?; // `macro_rules`
1386 self.expect(&token::Not)?; // `!`
1388 let ident = self.parse_ident()?;
1389 let body = self.parse_mac_args()?;
1390 if body.need_semicolon() && !self.eat(&token::Semi) {
1391 self.report_invalid_macro_expansion_item();
1394 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true }), None))
1397 pub(super) fn eat_macro_def(
1399 attrs: &[Attribute],
1402 ) -> PResult<'a, Option<P<Item>>> {
1403 let info = if self.eat_keyword(kw::Macro) {
1404 self.parse_item_decl_macro(lo)?
1405 } else if self.is_macro_rules_item() {
1406 self.parse_item_macro_rules(vis)?
1410 Ok(Some(self.mk_item_with_info(attrs.to_vec(), lo, vis.clone(), info)))
1413 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1415 VisibilityKind::Inherited => {}
1417 let mut err = if self.token.is_keyword(sym::macro_rules) {
1419 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1420 err.span_suggestion(
1422 "try exporting the macro",
1423 "#[macro_export]".to_owned(),
1424 Applicability::MaybeIncorrect, // speculative
1429 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1430 err.help("try adjusting the macro to put `pub` inside the invocation");
1438 fn report_invalid_macro_expansion_item(&self) {
1439 let has_close_delim = self
1442 .span_to_snippet(self.prev_span)
1443 .map(|s| s.ends_with(")") || s.ends_with("]"))
1446 let mut err = self.struct_span_err(
1448 "macros that expand to items must be delimited with braces or followed by a semicolon",
1451 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1452 if has_close_delim {
1453 err.multipart_suggestion(
1454 "change the delimiters to curly braces",
1456 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1457 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1459 Applicability::MaybeIncorrect,
1462 err.span_suggestion(
1464 "change the delimiters to curly braces",
1465 " { /* items */ }".to_string(),
1466 Applicability::HasPlaceholders,
1470 err.span_suggestion(
1471 self.prev_span.shrink_to_hi(),
1474 Applicability::MaybeIncorrect,
1479 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1480 /// it is, we try to parse the item and report error about nested types.
1481 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1482 if (self.token.is_keyword(kw::Enum)
1483 || self.token.is_keyword(kw::Struct)
1484 || self.token.is_keyword(kw::Union))
1485 && self.look_ahead(1, |t| t.is_ident())
1487 let kw_token = self.token.clone();
1488 let kw_str = pprust::token_to_string(&kw_token);
1489 let item = self.parse_item()?;
1491 self.struct_span_err(
1493 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1497 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1499 Applicability::MaybeIncorrect,
1502 // We successfully parsed the item but we must inform the caller about nested problem.
1514 attrs: Vec<Attribute>,
1516 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1520 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1522 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1523 type ReqName = fn(&token::Token) -> bool;
1525 /// Parsing of functions and methods.
1526 impl<'a> Parser<'a> {
1527 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1531 attrs: &mut Vec<Attribute>,
1533 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1534 let header = self.parse_fn_front_matter()?; // `const ... fn`
1535 let ident = self.parse_ident()?; // `foo`
1536 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1537 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1538 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1539 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1540 Ok((ident, FnSig { header, decl }, generics, body))
1543 /// Parse the "body" of a function.
1544 /// This can either be `;` when there's no body,
1545 /// or e.g. a block when the function is a provided one.
1549 attrs: &mut Vec<Attribute>,
1550 ) -> PResult<'a, Option<P<Block>>> {
1551 let (inner_attrs, body) = match self.token.kind {
1556 token::OpenDelim(token::Brace) => {
1557 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1560 token::Interpolated(ref nt) => match **nt {
1561 token::NtBlock(..) => {
1562 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1565 _ => return self.expected_semi_or_open_brace(),
1567 _ => return self.expected_semi_or_open_brace(),
1569 attrs.extend(inner_attrs);
1574 /// Is the current token the start of an `FnHeader` / not a valid parse?
1575 fn check_fn_front_matter(&mut self) -> bool {
1576 // We use an over-approximation here.
1577 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1578 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1579 self.check_keyword(kw::Fn) // Definitely an `fn`.
1580 // `$qual fn` or `$qual $qual`:
1581 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1582 && self.look_ahead(1, |t| {
1583 // ...qualified and then `fn`, e.g. `const fn`.
1584 t.is_keyword(kw::Fn)
1585 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1586 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1589 || self.check_keyword(kw::Extern)
1590 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1591 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1594 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1595 /// up to and including the `fn` keyword. The formal grammar is:
1598 /// Extern = "extern" StringLit ;
1599 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1600 /// FnFrontMatter = FnQual? "fn" ;
1602 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1603 let constness = self.parse_constness();
1604 let asyncness = self.parse_asyncness();
1605 let unsafety = self.parse_unsafety();
1606 let ext = self.parse_extern()?;
1608 if let Async::Yes { span, .. } = asyncness {
1609 self.ban_async_in_2015(span);
1612 if !self.eat_keyword(kw::Fn) {
1613 // It is possible for `expect_one_of` to recover given the contents of
1614 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1615 // account for this.
1616 if !self.expect_one_of(&[], &[])? {
1621 Ok(FnHeader { constness, unsafety, asyncness, ext })
1624 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1625 fn ban_async_in_2015(&self, span: Span) {
1626 if span.rust_2015() {
1627 let diag = self.diagnostic();
1628 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1629 .note("to use `async fn`, switch to Rust 2018")
1630 .help("set `edition = \"2018\"` in `Cargo.toml`")
1631 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1636 /// Parses the parameter list and result type of a function declaration.
1637 pub(super) fn parse_fn_decl(
1640 ret_allow_plus: AllowPlus,
1641 ) -> PResult<'a, P<FnDecl>> {
1643 inputs: self.parse_fn_params(req_name)?,
1644 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1648 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1649 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1650 let mut first_param = true;
1651 // Parse the arguments, starting out with `self` being allowed...
1652 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1653 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1655 let lo = p.prev_span;
1656 // Skip every token until next possible arg or end.
1657 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1658 // Create a placeholder argument for proper arg count (issue #34264).
1659 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1661 // ...now that we've parsed the first argument, `self` is no longer allowed.
1662 first_param = false;
1665 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1666 self.deduplicate_recovered_params_names(&mut params);
1670 /// Parses a single function parameter.
1672 /// - `self` is syntactically allowed when `first_param` holds.
1673 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1674 let lo = self.token.span;
1675 let attrs = self.parse_outer_attributes()?;
1677 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1678 if let Some(mut param) = self.parse_self_param()? {
1679 param.attrs = attrs.into();
1680 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1683 let is_name_required = match self.token.kind {
1684 token::DotDotDot => false,
1685 _ => req_name(&self.token),
1687 let (pat, ty) = if is_name_required || self.is_named_param() {
1688 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1690 let pat = self.parse_fn_param_pat()?;
1691 if let Err(mut err) = self.expect(&token::Colon) {
1692 return if let Some(ident) =
1693 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1696 Ok(dummy_arg(ident))
1702 self.eat_incorrect_doc_comment_for_param_type();
1703 (pat, self.parse_ty_for_param()?)
1705 debug!("parse_param_general ident_to_pat");
1706 let parser_snapshot_before_ty = self.clone();
1707 self.eat_incorrect_doc_comment_for_param_type();
1708 let mut ty = self.parse_ty_for_param();
1710 && self.token != token::Comma
1711 && self.token != token::CloseDelim(token::Paren)
1713 // This wasn't actually a type, but a pattern looking like a type,
1714 // so we are going to rollback and re-parse for recovery.
1715 ty = self.unexpected();
1719 let ident = Ident::new(kw::Invalid, self.prev_span);
1720 let bm = BindingMode::ByValue(Mutability::Not);
1721 let pat = self.mk_pat_ident(ty.span, bm, ident);
1724 // If this is a C-variadic argument and we hit an error, return the error.
1725 Err(err) if self.token == token::DotDotDot => return Err(err),
1726 // Recover from attempting to parse the argument as a type without pattern.
1729 mem::replace(self, parser_snapshot_before_ty);
1730 self.recover_arg_parse()?
1735 let span = lo.to(self.token.span);
1738 attrs: attrs.into(),
1739 id: ast::DUMMY_NODE_ID,
1740 is_placeholder: false,
1747 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1748 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1749 // Extract an identifier *after* having confirmed that the token is one.
1750 let expect_self_ident = |this: &mut Self| {
1751 match this.token.kind {
1752 // Preserve hygienic context.
1753 token::Ident(name, _) => {
1754 let span = this.token.span;
1756 Ident::new(name, span)
1758 _ => unreachable!(),
1761 // Is `self` `n` tokens ahead?
1762 let is_isolated_self = |this: &Self, n| {
1763 this.is_keyword_ahead(n, &[kw::SelfLower])
1764 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1766 // Is `mut self` `n` tokens ahead?
1767 let is_isolated_mut_self =
1768 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1769 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1770 let parse_self_possibly_typed = |this: &mut Self, m| {
1771 let eself_ident = expect_self_ident(this);
1772 let eself_hi = this.prev_span;
1773 let eself = if this.eat(&token::Colon) {
1774 SelfKind::Explicit(this.parse_ty()?, m)
1778 Ok((eself, eself_ident, eself_hi))
1780 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1781 let recover_self_ptr = |this: &mut Self| {
1782 let msg = "cannot pass `self` by raw pointer";
1783 let span = this.token.span;
1784 this.struct_span_err(span, msg).span_label(span, msg).emit();
1786 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1789 // Parse optional `self` parameter of a method.
1790 // Only a limited set of initial token sequences is considered `self` parameters; anything
1791 // else is parsed as a normal function parameter list, so some lookahead is required.
1792 let eself_lo = self.token.span;
1793 let (eself, eself_ident, eself_hi) = match self.token.kind {
1794 token::BinOp(token::And) => {
1795 let eself = if is_isolated_self(self, 1) {
1798 SelfKind::Region(None, Mutability::Not)
1799 } else if is_isolated_mut_self(self, 1) {
1803 SelfKind::Region(None, Mutability::Mut)
1804 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1807 let lt = self.expect_lifetime();
1808 SelfKind::Region(Some(lt), Mutability::Not)
1809 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1812 let lt = self.expect_lifetime();
1814 SelfKind::Region(Some(lt), Mutability::Mut)
1819 (eself, expect_self_ident(self), self.prev_span)
1822 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1824 recover_self_ptr(self)?
1826 // `*mut self` and `*const self`
1827 token::BinOp(token::Star)
1828 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1832 recover_self_ptr(self)?
1834 // `self` and `self: TYPE`
1835 token::Ident(..) if is_isolated_self(self, 0) => {
1836 parse_self_possibly_typed(self, Mutability::Not)?
1838 // `mut self` and `mut self: TYPE`
1839 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1841 parse_self_possibly_typed(self, Mutability::Mut)?
1843 _ => return Ok(None),
1846 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1847 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1850 fn is_named_param(&self) -> bool {
1851 let offset = match self.token.kind {
1852 token::Interpolated(ref nt) => match **nt {
1853 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1856 token::BinOp(token::And) | token::AndAnd => 1,
1857 _ if self.token.is_keyword(kw::Mut) => 1,
1861 self.look_ahead(offset, |t| t.is_ident())
1862 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1865 fn recover_first_param(&mut self) -> &'static str {
1867 .parse_outer_attributes()
1868 .and_then(|_| self.parse_self_param())
1869 .map_err(|mut e| e.cancel())
1871 Ok(Some(_)) => "method",