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.is_fn_front_matter() {
101 let (ident, sig, generics, body) =
102 self.parse_fn(&mut false, &mut attrs, &ParamCfg::FREE)?;
103 let kind = ItemKind::Fn(sig, generics, body);
104 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
107 if self.eat_keyword(kw::Extern) {
108 if self.eat_keyword(kw::Crate) {
110 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
113 let abi = self.parse_abi();
114 return Ok(Some(self.parse_item_foreign_mod(lo, abi, vis, attrs)?));
117 if self.is_static_global() {
120 let m = self.parse_mutability();
121 let info = self.parse_item_const(Some(m))?;
122 return self.mk_item_with_info(attrs, lo, vis, info);
125 if let Const::Yes(const_span) = self.parse_constness() {
127 if self.eat_keyword(kw::Mut) {
128 let prev_span = self.prev_span;
129 self.struct_span_err(prev_span, "const globals cannot be mutable")
130 .span_label(prev_span, "cannot be mutable")
133 "you might want to declare a static instead",
135 Applicability::MaybeIncorrect,
140 let info = self.parse_item_const(None)?;
141 return self.mk_item_with_info(attrs, lo, vis, info);
144 if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) {
146 let unsafety = self.parse_unsafety();
147 let info = self.parse_item_trait(lo, unsafety)?;
148 return self.mk_item_with_info(attrs, lo, vis, info);
151 if self.check_keyword(kw::Impl)
152 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
153 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
156 let defaultness = self.parse_defaultness();
157 let unsafety = self.parse_unsafety();
158 self.expect_keyword(kw::Impl)?;
159 let info = self.parse_item_impl(unsafety, defaultness)?;
160 return self.mk_item_with_info(attrs, lo, vis, info);
163 if self.eat_keyword(kw::Mod) {
165 let info = self.parse_item_mod(&attrs[..])?;
166 return self.mk_item_with_info(attrs, lo, vis, info);
169 if self.eat_keyword(kw::Type) {
171 let (ident, ty, generics) = self.parse_type_alias()?;
172 let kind = ItemKind::TyAlias(ty, generics);
173 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
176 if self.eat_keyword(kw::Enum) {
178 let info = self.parse_item_enum()?;
179 return self.mk_item_with_info(attrs, lo, vis, info);
182 if self.check_keyword(kw::Trait)
183 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
186 let info = self.parse_item_trait(lo, Unsafe::No)?;
187 return self.mk_item_with_info(attrs, lo, vis, info);
190 if self.eat_keyword(kw::Struct) {
192 let info = self.parse_item_struct()?;
193 return self.mk_item_with_info(attrs, lo, vis, info);
196 if self.is_union_item() {
199 let info = self.parse_item_union()?;
200 return self.mk_item_with_info(attrs, lo, vis, info);
203 if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? {
204 return Ok(Some(macro_def));
207 // Verify whether we have encountered a struct or method definition where the user forgot to
208 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
209 if vis.node.is_pub() && self.check_ident() && self.look_ahead(1, |t| *t != token::Not) {
210 // Space between `pub` keyword and the identifier
213 // ^^^ `sp` points here
214 let sp = self.prev_span.between(self.token.span);
215 let full_sp = self.prev_span.to(self.token.span);
216 let ident_sp = self.token.span;
217 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
218 // possible public struct definition where `struct` was forgotten
219 let ident = self.parse_ident().unwrap();
220 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
221 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
222 err.span_suggestion_short(
226 Applicability::MaybeIncorrect, // speculative
229 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
230 let ident = self.parse_ident().unwrap();
232 let kw_name = self.recover_first_param();
233 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
234 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
235 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
237 ("fn", kw_name, false)
238 } else if self.check(&token::OpenDelim(token::Brace)) {
240 ("fn", kw_name, false)
241 } else if self.check(&token::Colon) {
245 ("fn` or `struct", "function or struct", true)
248 let msg = format!("missing `{}` for {} definition", kw, kw_name);
249 let mut err = self.struct_span_err(sp, &msg);
251 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
253 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
254 err.span_suggestion_short(
258 Applicability::MachineApplicable,
261 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
264 "if you meant to call a macro, try",
265 format!("{}!", snippet),
266 // this is the `ambiguous` conditional branch
267 Applicability::MaybeIncorrect,
271 "if you meant to call a macro, remove the `pub` \
272 and add a trailing `!` after the identifier",
277 } else if self.look_ahead(1, |t| *t == token::Lt) {
278 let ident = self.parse_ident().unwrap();
279 self.eat_to_tokens(&[&token::Gt]);
281 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
282 ("fn", self.recover_first_param(), false)
283 } else if self.check(&token::OpenDelim(token::Brace)) {
284 ("struct", "struct", false)
286 ("fn` or `struct", "function or struct", true)
288 let msg = format!("missing `{}` for {} definition", kw, kw_name);
289 let mut err = self.struct_span_err(sp, &msg);
291 err.span_suggestion_short(
293 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
295 Applicability::MachineApplicable,
301 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis)
304 pub(super) fn mk_item_with_info(
306 attrs: Vec<Attribute>,
310 ) -> PResult<'a, Option<P<Item>>> {
311 let (ident, item, extra_attrs) = info;
312 let span = lo.to(self.prev_span);
313 let attrs = Self::maybe_append(attrs, extra_attrs);
314 Ok(Some(self.mk_item(span, ident, item, vis, attrs)))
317 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
318 if let Some(ref mut rhs) = rhs {
324 /// This is the fall-through for parsing items.
325 fn parse_macro_use_or_failure(
327 attrs: Vec<Attribute>,
328 macros_allowed: bool,
329 attributes_allowed: bool,
331 visibility: Visibility,
332 ) -> PResult<'a, Option<P<Item>>> {
334 && self.token.is_path_start()
335 && !(self.is_async_fn() && self.token.span.rust_2015())
337 // MACRO INVOCATION ITEM
339 let prev_span = self.prev_span;
340 self.complain_if_pub_macro(&visibility.node, prev_span);
343 let path = self.parse_path(PathStyle::Mod)?;
344 self.expect(&token::Not)?;
345 let args = self.parse_mac_args()?;
346 if args.need_semicolon() && !self.eat(&token::Semi) {
347 self.report_invalid_macro_expansion_item();
350 let hi = self.prev_span;
351 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
353 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
354 return Ok(Some(item));
357 // FAILURE TO PARSE ITEM
358 match visibility.node {
359 VisibilityKind::Inherited => {}
360 _ => return Err(self.struct_span_err(self.prev_span, "unmatched visibility `pub`")),
363 if !attributes_allowed && !attrs.is_empty() {
364 self.expected_item_err(&attrs)?;
369 /// Emits an expected-item-after-attributes error.
370 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
371 let message = match attrs.last() {
372 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
373 "expected item after doc comment"
375 _ => "expected item after attributes",
378 let mut err = self.struct_span_err(self.prev_span, message);
379 if attrs.last().unwrap().is_doc_comment() {
380 err.span_label(self.prev_span, "this doc comment doesn't document anything");
385 pub(super) fn is_async_fn(&self) -> bool {
386 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
389 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
390 fn parse_assoc_macro_invoc(
393 vis: Option<&Visibility>,
395 ) -> PResult<'a, Option<Mac>> {
396 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
397 let prev_span = self.prev_span;
398 let path = self.parse_path(PathStyle::Mod)?;
400 if path.segments.len() == 1 {
401 if !self.eat(&token::Not) {
402 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
405 self.expect(&token::Not)?;
408 if let Some(vis) = vis {
409 self.complain_if_pub_macro(&vis.node, prev_span);
414 // eat a matched-delimiter token tree:
415 let args = self.parse_mac_args()?;
416 if args.need_semicolon() {
420 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
426 fn missing_assoc_item_kind_err(
430 ) -> DiagnosticBuilder<'a> {
431 let expected_kinds = if item_type == "extern" {
432 "missing `fn`, `type`, or `static`"
434 "missing `fn`, `type`, or `const`"
437 // Given this code `path(`, it seems like this is not
438 // setting the visibility of a macro invocation, but rather
439 // a mistyped method declaration.
440 // Create a diagnostic pointing out that `fn` is missing.
442 // x | pub path(&self) {
443 // | ^ missing `fn`, `type`, or `const`
445 // ^^ `sp` below will point to this
446 let sp = prev_span.between(self.prev_span);
448 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
449 err.span_label(sp, expected_kinds);
453 /// Parses an implementation item, `impl` keyword is already parsed.
455 /// impl<'a, T> TYPE { /* impl items */ }
456 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
457 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
458 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
460 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
461 /// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
462 /// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
466 defaultness: Defaultness,
467 ) -> PResult<'a, ItemInfo> {
468 // First, parse generic parameters if necessary.
469 let mut generics = if self.choose_generics_over_qpath() {
470 self.parse_generics()?
472 let mut generics = Generics::default();
474 // /\ this is where `generics.span` should point when there are no type params.
475 generics.span = self.prev_span.shrink_to_hi();
479 let constness = self.parse_constness();
480 if let Const::Yes(span) = constness {
481 self.sess.gated_spans.gate(sym::const_trait_impl, span);
484 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
485 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
487 ast::ImplPolarity::Negative
489 ast::ImplPolarity::Positive
492 // Parse both types and traits as a type, then reinterpret if necessary.
493 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
494 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
496 let span = self.prev_span.between(self.token.span);
497 self.struct_span_err(span, "missing trait in a trait impl").emit();
498 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
503 // If `for` is missing we try to recover.
504 let has_for = self.eat_keyword(kw::For);
505 let missing_for_span = self.prev_span.between(self.token.span);
507 let ty_second = if self.token == token::DotDot {
508 // We need to report this error after `cfg` expansion for compatibility reasons
509 self.bump(); // `..`, do not add it to expected tokens
510 Some(self.mk_ty(self.prev_span, TyKind::Err))
511 } else if has_for || self.token.can_begin_type() {
512 Some(self.parse_ty()?)
517 generics.where_clause = self.parse_where_clause()?;
519 let (impl_items, attrs) = self.parse_impl_body()?;
521 let item_kind = match ty_second {
523 // impl Trait for Type
525 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
526 .span_suggestion_short(
530 Applicability::MachineApplicable,
535 let ty_first = ty_first.into_inner();
536 let path = match ty_first.kind {
537 // This notably includes paths passed through `ty` macro fragments (#46438).
538 TyKind::Path(None, path) => path,
540 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
541 err_path(ty_first.span)
544 let trait_ref = TraitRef { path, ref_id: ty_first.id };
552 of_trait: Some(trait_ref),
572 Ok((Ident::invalid(), item_kind, Some(attrs)))
575 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<P<AssocItem>>, Vec<Attribute>)> {
576 self.expect(&token::OpenDelim(token::Brace))?;
577 let attrs = self.parse_inner_attributes()?;
579 let mut impl_items = Vec::new();
580 while !self.eat(&token::CloseDelim(token::Brace)) {
581 let mut at_end = false;
582 match self.parse_impl_item(&mut at_end) {
583 Ok(impl_item) => impl_items.push(impl_item),
587 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
593 Ok((impl_items, attrs))
596 /// Parses defaultness (i.e., `default` or nothing).
597 fn parse_defaultness(&mut self) -> Defaultness {
598 // `pub` is included for better error messages
599 if self.check_keyword(kw::Default)
600 && self.is_keyword_ahead(
614 self.bump(); // `default`
621 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
622 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafe) -> PResult<'a, ItemInfo> {
623 // Parse optional `auto` prefix.
624 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
626 self.expect_keyword(kw::Trait)?;
627 let ident = self.parse_ident()?;
628 let mut tps = self.parse_generics()?;
630 // Parse optional colon and supertrait bounds.
631 let had_colon = self.eat(&token::Colon);
632 let span_at_colon = self.prev_span;
634 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
636 let span_before_eq = self.prev_span;
637 if self.eat(&token::Eq) {
638 // It's a trait alias.
640 let span = span_at_colon.to(span_before_eq);
641 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
644 let bounds = self.parse_generic_bounds(None)?;
645 tps.where_clause = self.parse_where_clause()?;
648 let whole_span = lo.to(self.prev_span);
649 if is_auto == IsAuto::Yes {
650 let msg = "trait aliases cannot be `auto`";
651 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
653 if let Unsafe::Yes(_) = unsafety {
654 let msg = "trait aliases cannot be `unsafe`";
655 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
658 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
660 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
662 // It's a normal trait.
663 tps.where_clause = self.parse_where_clause()?;
664 self.expect(&token::OpenDelim(token::Brace))?;
665 let mut trait_items = vec![];
666 while !self.eat(&token::CloseDelim(token::Brace)) {
667 if let token::DocComment(_) = self.token.kind {
668 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
673 "found a documentation comment that doesn't document anything",
676 "doc comments must come before what they document, maybe a \
677 comment was intended with `//`?",
684 let mut at_end = false;
685 match self.parse_trait_item(&mut at_end) {
686 Ok(item) => trait_items.push(item),
690 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
696 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
700 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
701 maybe_whole!(self, NtImplItem, |x| x);
702 self.parse_assoc_item(at_end, |_| true)
705 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
706 maybe_whole!(self, NtTraitItem, |x| x);
707 // This is somewhat dubious; We don't want to allow
708 // param names to be left off if there is a definition...
710 // We don't allow param names to be left off in edition 2018.
711 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
714 /// Parses associated items.
718 is_name_required: fn(&token::Token) -> bool,
719 ) -> PResult<'a, P<AssocItem>> {
720 let attrs = self.parse_outer_attributes()?;
721 let mut unclosed_delims = vec![];
722 let (mut item, tokens) = self.collect_tokens(|this| {
723 let item = this.parse_assoc_item_(at_end, attrs, is_name_required);
724 unclosed_delims.append(&mut this.unclosed_delims);
727 self.unclosed_delims.append(&mut unclosed_delims);
728 // See `parse_item` for why this clause is here.
729 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
730 item.tokens = Some(tokens);
735 fn parse_assoc_item_(
738 mut attrs: Vec<Attribute>,
739 is_name_required: fn(&token::Token) -> bool,
740 ) -> PResult<'a, AssocItem> {
741 let lo = self.token.span;
742 let vis = self.parse_visibility(FollowedByType::No)?;
743 let defaultness = self.parse_defaultness();
744 let (name, kind, generics) = if self.eat_keyword(kw::Type) {
745 self.parse_assoc_ty()?
746 } else if self.is_fn_front_matter() {
747 let cfg = ParamCfg { is_name_required };
748 let (ident, sig, generics, body) = self.parse_fn(at_end, &mut attrs, &cfg)?;
749 (ident, AssocItemKind::Fn(sig, body), generics)
750 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
751 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
753 self.parse_assoc_const()?
758 span: lo.to(self.prev_span),
769 /// This parses the grammar:
771 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
772 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
773 self.expect_keyword(kw::Const)?;
774 let ident = self.parse_ident()?;
775 self.expect(&token::Colon)?;
776 let ty = self.parse_ty()?;
777 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
779 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
782 /// Parses the following grammar:
784 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
785 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
786 let ident = self.parse_ident()?;
787 let mut generics = self.parse_generics()?;
789 // Parse optional colon and param bounds.
791 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
792 generics.where_clause = self.parse_where_clause()?;
794 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
797 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
800 /// Parses a `UseTree`.
803 /// USE_TREE = [`::`] `*` |
804 /// [`::`] `{` USE_TREE_LIST `}` |
806 /// PATH `::` `{` USE_TREE_LIST `}` |
807 /// PATH [`as` IDENT]
809 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
810 let lo = self.token.span;
812 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
813 let kind = if self.check(&token::OpenDelim(token::Brace))
814 || self.check(&token::BinOp(token::Star))
815 || self.is_import_coupler()
817 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
818 let mod_sep_ctxt = self.token.span.ctxt();
819 if self.eat(&token::ModSep) {
822 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
825 self.parse_use_tree_glob_or_nested()?
827 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
828 prefix = self.parse_path(PathStyle::Mod)?;
830 if self.eat(&token::ModSep) {
831 self.parse_use_tree_glob_or_nested()?
833 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
837 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
840 /// Parses `*` or `{...}`.
841 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
842 Ok(if self.eat(&token::BinOp(token::Star)) {
845 UseTreeKind::Nested(self.parse_use_tree_list()?)
849 /// Parses a `UseTreeKind::Nested(list)`.
852 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
854 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
855 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
859 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
860 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
863 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
864 match self.token.kind {
865 token::Ident(name, false) if name == kw::Underscore => {
866 let span = self.token.span;
868 Ok(Ident::new(name, span))
870 _ => self.parse_ident(),
874 /// Parses `extern crate` links.
879 /// extern crate foo;
880 /// extern crate bar as foo;
882 fn parse_item_extern_crate(
885 visibility: Visibility,
886 attrs: Vec<Attribute>,
887 ) -> PResult<'a, P<Item>> {
888 // Accept `extern crate name-like-this` for better diagnostics
889 let orig_name = self.parse_crate_name_with_dashes()?;
890 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
891 (rename, Some(orig_name.name))
897 let span = lo.to(self.prev_span);
898 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
901 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
902 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
903 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
905 let mut ident = if self.token.is_keyword(kw::SelfLower) {
906 self.parse_path_segment_ident()
910 let mut idents = vec![];
911 let mut replacement = vec![];
912 let mut fixed_crate_name = false;
913 // Accept `extern crate name-like-this` for better diagnostics.
914 let dash = token::BinOp(token::BinOpToken::Minus);
915 if self.token == dash {
916 // Do not include `-` as part of the expected tokens list.
917 while self.eat(&dash) {
918 fixed_crate_name = true;
919 replacement.push((self.prev_span, "_".to_string()));
920 idents.push(self.parse_ident()?);
923 if fixed_crate_name {
924 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
925 let mut fixed_name = format!("{}", ident.name);
927 fixed_name.push_str(&format!("_{}", part.name));
929 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
931 self.struct_span_err(fixed_name_sp, error_msg)
932 .span_label(fixed_name_sp, "dash-separated idents are not valid")
933 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
939 /// Parses `extern` for foreign ABIs modules.
941 /// `extern` is expected to have been
942 /// consumed before calling this method.
946 /// ```ignore (only-for-syntax-highlight)
950 fn parse_item_foreign_mod(
954 visibility: Visibility,
955 mut attrs: Vec<Attribute>,
956 ) -> PResult<'a, P<Item>> {
957 self.expect(&token::OpenDelim(token::Brace))?;
959 attrs.extend(self.parse_inner_attributes()?);
961 let mut foreign_items = vec![];
962 while !self.eat(&token::CloseDelim(token::Brace)) {
963 foreign_items.push(self.parse_foreign_item()?);
966 let prev_span = self.prev_span;
967 let m = ast::ForeignMod { abi, items: foreign_items };
968 let invalid = Ident::invalid();
969 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
972 /// Parses a foreign item.
973 pub fn parse_foreign_item(&mut self) -> PResult<'a, P<ForeignItem>> {
974 maybe_whole!(self, NtForeignItem, |ni| ni);
976 let mut attrs = self.parse_outer_attributes()?;
977 let lo = self.token.span;
978 let vis = self.parse_visibility(FollowedByType::No)?;
980 if self.check_keyword(kw::Type) {
982 self.parse_item_foreign_type(vis, lo, attrs)
983 } else if self.is_fn_front_matter() {
984 // FOREIGN FUNCTION ITEM
985 let (ident, sig, generics, body) =
986 self.parse_fn(&mut false, &mut attrs, &ParamCfg::FREE)?;
987 let kind = ForeignItemKind::Fn(sig, generics, body);
988 let span = lo.to(self.prev_span);
989 Ok(P(ast::ForeignItem {
998 } else if self.is_static_global() {
999 // FOREIGN STATIC ITEM
1000 self.bump(); // `static`
1001 self.parse_item_foreign_static(vis, lo, attrs)
1002 } else if self.token.is_keyword(kw::Const) {
1003 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
1004 self.bump(); // `const`
1005 self.struct_span_err(self.prev_span, "extern items cannot be `const`")
1008 "try using a static value",
1009 "static".to_owned(),
1010 Applicability::MachineApplicable,
1013 self.parse_item_foreign_static(vis, lo, attrs)
1014 } else if let Some(mac) = self.parse_assoc_macro_invoc("extern", Some(&vis), &mut false)? {
1015 let kind = ForeignItemKind::Macro(mac);
1016 let span = lo.to(self.prev_span);
1017 let ident = Ident::invalid();
1018 Ok(P(ForeignItem { ident, span, id: DUMMY_NODE_ID, attrs, vis, kind, tokens: None }))
1020 if !attrs.is_empty() {
1021 self.expected_item_err(&attrs)?;
1027 /// Parses a static item from a foreign module.
1028 /// Assumes that the `static` keyword is already parsed.
1029 fn parse_item_foreign_static(
1031 vis: ast::Visibility,
1033 attrs: Vec<Attribute>,
1034 ) -> PResult<'a, P<ForeignItem>> {
1035 let mutbl = self.parse_mutability();
1036 let ident = self.parse_ident()?;
1037 self.expect(&token::Colon)?;
1038 let ty = self.parse_ty()?;
1039 let hi = self.token.span;
1040 self.expect_semi()?;
1044 kind: ForeignItemKind::Static(ty, mutbl),
1052 /// Parses a type from a foreign module.
1053 fn parse_item_foreign_type(
1055 vis: ast::Visibility,
1057 attrs: Vec<Attribute>,
1058 ) -> PResult<'a, P<ForeignItem>> {
1059 self.expect_keyword(kw::Type)?;
1061 let ident = self.parse_ident()?;
1062 let hi = self.token.span;
1063 self.expect_semi()?;
1064 Ok(P(ast::ForeignItem {
1067 kind: ForeignItemKind::Ty,
1075 fn is_static_global(&mut self) -> bool {
1076 if self.check_keyword(kw::Static) {
1077 // Check if this could be a closure.
1078 !self.look_ahead(1, |token| {
1079 if token.is_keyword(kw::Move) {
1083 token::BinOp(token::Or) | token::OrOr => true,
1092 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1093 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1095 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1096 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1097 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1099 // Parse the type of a `const` or `static mut?` item.
1100 // That is, the `":" $ty` fragment.
1101 let ty = if self.token == token::Eq {
1102 self.recover_missing_const_type(id, m)
1104 // Not `=` so expect `":"" $ty` as usual.
1105 self.expect(&token::Colon)?;
1109 self.expect(&token::Eq)?;
1110 let e = self.parse_expr()?;
1111 self.expect_semi()?;
1112 let item = match m {
1113 Some(m) => ItemKind::Static(ty, m, e),
1114 None => ItemKind::Const(ty, e),
1116 Ok((id, item, None))
1119 /// We were supposed to parse `:` but instead, we're already at `=`.
1120 /// This means that the type is missing.
1121 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1122 // Construct the error and stash it away with the hope
1123 // that typeck will later enrich the error with a type.
1124 let kind = match m {
1125 Some(Mutability::Mut) => "static mut",
1126 Some(Mutability::Not) => "static",
1129 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1130 err.span_suggestion(
1132 "provide a type for the item",
1133 format!("{}: <type>", id),
1134 Applicability::HasPlaceholders,
1136 err.stash(id.span, StashKey::ItemNoType);
1138 // The user intended that the type be inferred,
1139 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1140 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1143 /// Parses the grammar:
1144 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1145 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1146 let ident = self.parse_ident()?;
1147 let mut tps = self.parse_generics()?;
1148 tps.where_clause = self.parse_where_clause()?;
1149 self.expect(&token::Eq)?;
1150 let ty = self.parse_ty()?;
1151 self.expect_semi()?;
1152 Ok((ident, ty, tps))
1155 /// Parses an enum declaration.
1156 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1157 let id = self.parse_ident()?;
1158 let mut generics = self.parse_generics()?;
1159 generics.where_clause = self.parse_where_clause()?;
1162 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1163 self.recover_stmt();
1167 let enum_definition =
1168 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1169 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1172 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1173 let variant_attrs = self.parse_outer_attributes()?;
1174 let vlo = self.token.span;
1176 let vis = self.parse_visibility(FollowedByType::No)?;
1177 if !self.recover_nested_adt_item(kw::Enum)? {
1180 let ident = self.parse_ident()?;
1182 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1183 // Parse a struct variant.
1184 let (fields, recovered) = self.parse_record_struct_body()?;
1185 VariantData::Struct(fields, recovered)
1186 } else if self.check(&token::OpenDelim(token::Paren)) {
1187 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1189 VariantData::Unit(DUMMY_NODE_ID)
1193 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1195 let vr = ast::Variant {
1199 attrs: variant_attrs,
1202 span: vlo.to(self.prev_span),
1203 is_placeholder: false,
1209 /// Parses `struct Foo { ... }`.
1210 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1211 let class_name = self.parse_ident()?;
1213 let mut generics = self.parse_generics()?;
1215 // There is a special case worth noting here, as reported in issue #17904.
1216 // If we are parsing a tuple struct it is the case that the where clause
1217 // should follow the field list. Like so:
1219 // struct Foo<T>(T) where T: Copy;
1221 // If we are parsing a normal record-style struct it is the case
1222 // that the where clause comes before the body, and after the generics.
1223 // So if we look ahead and see a brace or a where-clause we begin
1224 // parsing a record style struct.
1226 // Otherwise if we look ahead and see a paren we parse a tuple-style
1229 let vdata = if self.token.is_keyword(kw::Where) {
1230 generics.where_clause = self.parse_where_clause()?;
1231 if self.eat(&token::Semi) {
1232 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1233 VariantData::Unit(DUMMY_NODE_ID)
1235 // If we see: `struct Foo<T> where T: Copy { ... }`
1236 let (fields, recovered) = self.parse_record_struct_body()?;
1237 VariantData::Struct(fields, recovered)
1239 // No `where` so: `struct Foo<T>;`
1240 } else if self.eat(&token::Semi) {
1241 VariantData::Unit(DUMMY_NODE_ID)
1242 // Record-style struct definition
1243 } else if self.token == token::OpenDelim(token::Brace) {
1244 let (fields, recovered) = self.parse_record_struct_body()?;
1245 VariantData::Struct(fields, recovered)
1246 // Tuple-style struct definition with optional where-clause.
1247 } else if self.token == token::OpenDelim(token::Paren) {
1248 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1249 generics.where_clause = self.parse_where_clause()?;
1250 self.expect_semi()?;
1253 let token_str = super::token_descr(&self.token);
1255 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1258 let mut err = self.struct_span_err(self.token.span, msg);
1259 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1263 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1266 /// Parses `union Foo { ... }`.
1267 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1268 let class_name = self.parse_ident()?;
1270 let mut generics = self.parse_generics()?;
1272 let vdata = if self.token.is_keyword(kw::Where) {
1273 generics.where_clause = self.parse_where_clause()?;
1274 let (fields, recovered) = self.parse_record_struct_body()?;
1275 VariantData::Struct(fields, recovered)
1276 } else if self.token == token::OpenDelim(token::Brace) {
1277 let (fields, recovered) = self.parse_record_struct_body()?;
1278 VariantData::Struct(fields, recovered)
1280 let token_str = super::token_descr(&self.token);
1281 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1282 let mut err = self.struct_span_err(self.token.span, msg);
1283 err.span_label(self.token.span, "expected `where` or `{` after union name");
1287 Ok((class_name, ItemKind::Union(vdata, generics), None))
1290 pub(super) fn is_union_item(&self) -> bool {
1291 self.token.is_keyword(kw::Union)
1292 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1295 fn parse_record_struct_body(
1297 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1298 let mut fields = Vec::new();
1299 let mut recovered = false;
1300 if self.eat(&token::OpenDelim(token::Brace)) {
1301 while self.token != token::CloseDelim(token::Brace) {
1302 let field = self.parse_struct_decl_field().map_err(|e| {
1303 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1308 Ok(field) => fields.push(field),
1315 self.eat(&token::CloseDelim(token::Brace));
1317 let token_str = super::token_descr(&self.token);
1318 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1319 let mut err = self.struct_span_err(self.token.span, msg);
1320 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1324 Ok((fields, recovered))
1327 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1328 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1329 // Unit like structs are handled in parse_item_struct function
1330 self.parse_paren_comma_seq(|p| {
1331 let attrs = p.parse_outer_attributes()?;
1332 let lo = p.token.span;
1333 let vis = p.parse_visibility(FollowedByType::Yes)?;
1334 let ty = p.parse_ty()?;
1336 span: lo.to(ty.span),
1342 is_placeholder: false,
1348 /// Parses an element of a struct declaration.
1349 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1350 let attrs = self.parse_outer_attributes()?;
1351 let lo = self.token.span;
1352 let vis = self.parse_visibility(FollowedByType::No)?;
1353 self.parse_single_struct_field(lo, vis, attrs)
1356 /// Parses a structure field declaration.
1357 fn parse_single_struct_field(
1361 attrs: Vec<Attribute>,
1362 ) -> PResult<'a, StructField> {
1363 let mut seen_comma: bool = false;
1364 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1365 if self.token == token::Comma {
1368 match self.token.kind {
1372 token::CloseDelim(token::Brace) => {}
1373 token::DocComment(_) => {
1374 let previous_span = self.prev_span;
1375 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1376 self.bump(); // consume the doc comment
1377 let comma_after_doc_seen = self.eat(&token::Comma);
1378 // `seen_comma` is always false, because we are inside doc block
1379 // condition is here to make code more readable
1380 if seen_comma == false && comma_after_doc_seen == true {
1383 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1386 if seen_comma == false {
1387 let sp = self.sess.source_map().next_point(previous_span);
1388 err.span_suggestion(
1390 "missing comma here",
1392 Applicability::MachineApplicable,
1399 let sp = self.prev_span.shrink_to_hi();
1400 let mut err = self.struct_span_err(
1402 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1404 if self.token.is_ident() {
1405 // This is likely another field; emit the diagnostic and keep going
1406 err.span_suggestion(
1408 "try adding a comma",
1410 Applicability::MachineApplicable,
1421 /// Parses a structure field.
1422 fn parse_name_and_ty(
1426 attrs: Vec<Attribute>,
1427 ) -> PResult<'a, StructField> {
1428 let name = self.parse_ident()?;
1429 self.expect(&token::Colon)?;
1430 let ty = self.parse_ty()?;
1432 span: lo.to(self.prev_span),
1438 is_placeholder: false,
1442 pub(super) fn eat_macro_def(
1444 attrs: &[Attribute],
1447 ) -> PResult<'a, Option<P<Item>>> {
1448 let (ident, def) = if self.eat_keyword(kw::Macro) {
1449 let ident = self.parse_ident()?;
1450 let body = if self.check(&token::OpenDelim(token::Brace)) {
1451 self.parse_mac_args()?
1452 } else if self.check(&token::OpenDelim(token::Paren)) {
1453 let params = self.parse_token_tree();
1454 let pspan = params.span();
1455 let body = if self.check(&token::OpenDelim(token::Brace)) {
1456 self.parse_token_tree()
1458 return self.unexpected();
1460 let bspan = body.span();
1461 let tokens = TokenStream::new(vec![
1463 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1466 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1467 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1469 return self.unexpected();
1472 (ident, ast::MacroDef { body, legacy: false })
1473 } else if self.check_keyword(sym::macro_rules)
1474 && self.look_ahead(1, |t| *t == token::Not)
1475 && self.look_ahead(2, |t| t.is_ident())
1477 let prev_span = self.prev_span;
1478 self.complain_if_pub_macro(&vis.node, prev_span);
1482 let ident = self.parse_ident()?;
1483 let body = self.parse_mac_args()?;
1484 if body.need_semicolon() && !self.eat(&token::Semi) {
1485 self.report_invalid_macro_expansion_item();
1488 (ident, ast::MacroDef { body, legacy: true })
1493 let span = lo.to(self.prev_span);
1496 self.sess.gated_spans.gate(sym::decl_macro, span);
1499 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1502 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1504 VisibilityKind::Inherited => {}
1506 let mut err = if self.token.is_keyword(sym::macro_rules) {
1508 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1509 err.span_suggestion(
1511 "try exporting the macro",
1512 "#[macro_export]".to_owned(),
1513 Applicability::MaybeIncorrect, // speculative
1518 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1519 err.help("try adjusting the macro to put `pub` inside the invocation");
1527 fn report_invalid_macro_expansion_item(&self) {
1528 let has_close_delim = self
1531 .span_to_snippet(self.prev_span)
1532 .map(|s| s.ends_with(")") || s.ends_with("]"))
1535 let mut err = self.struct_span_err(
1537 "macros that expand to items must be delimited with braces or followed by a semicolon",
1540 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1541 if has_close_delim {
1542 err.multipart_suggestion(
1543 "change the delimiters to curly braces",
1545 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1546 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1548 Applicability::MaybeIncorrect,
1551 err.span_suggestion(
1553 "change the delimiters to curly braces",
1554 " { /* items */ }".to_string(),
1555 Applicability::HasPlaceholders,
1559 err.span_suggestion(
1560 self.prev_span.shrink_to_hi(),
1563 Applicability::MaybeIncorrect,
1568 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1569 /// it is, we try to parse the item and report error about nested types.
1570 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1571 if (self.token.is_keyword(kw::Enum)
1572 || self.token.is_keyword(kw::Struct)
1573 || self.token.is_keyword(kw::Union))
1574 && self.look_ahead(1, |t| t.is_ident())
1576 let kw_token = self.token.clone();
1577 let kw_str = pprust::token_to_string(&kw_token);
1578 let item = self.parse_item()?;
1580 self.struct_span_err(
1582 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1586 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1588 Applicability::MaybeIncorrect,
1591 // We successfully parsed the item but we must inform the caller about nested problem.
1603 attrs: Vec<Attribute>,
1605 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1609 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1610 pub(super) struct ParamCfg {
1611 /// `is_name_required` decides if, per-parameter,
1612 /// the parameter must have a pattern or just a type.
1613 pub is_name_required: fn(&token::Token) -> bool,
1617 /// Configuration for a free function in the sense that it is not associated.
1618 const FREE: Self = ParamCfg { is_name_required: |_| true };
1621 /// Parsing of functions and methods.
1622 impl<'a> Parser<'a> {
1623 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1627 attrs: &mut Vec<Attribute>,
1629 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1630 let header = self.parse_fn_front_matter()?; // `const ... fn`
1631 let ident = self.parse_ident()?; // `foo`
1632 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1633 let decl = self.parse_fn_decl(cfg, AllowPlus::Yes)?; // `(p: u8, ...)`
1634 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1635 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1636 Ok((ident, FnSig { header, decl }, generics, body))
1639 /// Parse the "body" of a function.
1640 /// This can either be `;` when there's no body,
1641 /// or e.g. a block when the function is a provided one.
1645 attrs: &mut Vec<Attribute>,
1646 ) -> PResult<'a, Option<P<Block>>> {
1647 let (inner_attrs, body) = match self.token.kind {
1652 token::OpenDelim(token::Brace) => {
1653 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1656 token::Interpolated(ref nt) => match **nt {
1657 token::NtBlock(..) => {
1658 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1661 _ => return self.expected_semi_or_open_brace(),
1663 _ => return self.expected_semi_or_open_brace(),
1665 attrs.extend(inner_attrs);
1670 /// Is the current token the start of an `FnHeader` / not a valid parse?
1671 fn is_fn_front_matter(&mut self) -> bool {
1672 // We use an over-approximation here.
1673 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1674 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1675 self.check_keyword(kw::Fn) // Definitely an `fn`.
1676 // `$qual fn` or `$qual $qual`:
1677 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1678 && self.look_ahead(1, |t| {
1679 // ...qualified and then `fn`, e.g. `const fn`.
1680 t.is_keyword(kw::Fn)
1681 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1682 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1685 || self.check_keyword(kw::Extern)
1686 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1687 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1690 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1691 /// up to and including the `fn` keyword. The formal grammar is:
1694 /// Extern = "extern" StringLit ;
1695 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1696 /// FnFrontMatter = FnQual? "fn" ;
1698 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1699 let constness = self.parse_constness();
1700 let asyncness = self.parse_asyncness();
1701 let unsafety = self.parse_unsafety();
1702 let ext = self.parse_extern()?;
1704 if let Async::Yes { span, .. } = asyncness {
1705 self.ban_async_in_2015(span);
1708 if !self.eat_keyword(kw::Fn) {
1709 // It is possible for `expect_one_of` to recover given the contents of
1710 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1711 // account for this.
1712 if !self.expect_one_of(&[], &[])? {
1717 Ok(FnHeader { constness, unsafety, asyncness, ext })
1720 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1721 fn ban_async_in_2015(&self, span: Span) {
1722 if span.rust_2015() {
1723 let diag = self.diagnostic();
1724 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1725 .note("to use `async fn`, switch to Rust 2018")
1726 .help("set `edition = \"2018\"` in `Cargo.toml`")
1727 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1732 /// Parses the parameter list and result type of a function declaration.
1733 pub(super) fn parse_fn_decl(
1736 ret_allow_plus: AllowPlus,
1737 ) -> PResult<'a, P<FnDecl>> {
1739 inputs: self.parse_fn_params(cfg)?,
1740 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1744 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1745 fn parse_fn_params(&mut self, cfg: &ParamCfg) -> PResult<'a, Vec<Param>> {
1746 let mut first_param = true;
1747 // Parse the arguments, starting out with `self` being allowed...
1748 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1749 let param = p.parse_param_general(&cfg, first_param).or_else(|mut e| {
1751 let lo = p.prev_span;
1752 // Skip every token until next possible arg or end.
1753 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1754 // Create a placeholder argument for proper arg count (issue #34264).
1755 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1757 // ...now that we've parsed the first argument, `self` is no longer allowed.
1758 first_param = false;
1761 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1762 self.deduplicate_recovered_params_names(&mut params);
1766 /// Parses a single function parameter.
1768 /// - `self` is syntactically allowed when `first_param` holds.
1769 fn parse_param_general(&mut self, cfg: &ParamCfg, first_param: bool) -> PResult<'a, Param> {
1770 let lo = self.token.span;
1771 let attrs = self.parse_outer_attributes()?;
1773 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1774 if let Some(mut param) = self.parse_self_param()? {
1775 param.attrs = attrs.into();
1776 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1779 let is_name_required = match self.token.kind {
1780 token::DotDotDot => false,
1781 _ => (cfg.is_name_required)(&self.token),
1783 let (pat, ty) = if is_name_required || self.is_named_param() {
1784 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1786 let pat = self.parse_fn_param_pat()?;
1787 if let Err(mut err) = self.expect(&token::Colon) {
1788 return if let Some(ident) =
1789 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1792 Ok(dummy_arg(ident))
1798 self.eat_incorrect_doc_comment_for_param_type();
1799 (pat, self.parse_ty_for_param()?)
1801 debug!("parse_param_general ident_to_pat");
1802 let parser_snapshot_before_ty = self.clone();
1803 self.eat_incorrect_doc_comment_for_param_type();
1804 let mut ty = self.parse_ty_for_param();
1806 && self.token != token::Comma
1807 && self.token != token::CloseDelim(token::Paren)
1809 // This wasn't actually a type, but a pattern looking like a type,
1810 // so we are going to rollback and re-parse for recovery.
1811 ty = self.unexpected();
1815 let ident = Ident::new(kw::Invalid, self.prev_span);
1816 let bm = BindingMode::ByValue(Mutability::Not);
1817 let pat = self.mk_pat_ident(ty.span, bm, ident);
1820 // If this is a C-variadic argument and we hit an error, return the error.
1821 Err(err) if self.token == token::DotDotDot => return Err(err),
1822 // Recover from attempting to parse the argument as a type without pattern.
1825 mem::replace(self, parser_snapshot_before_ty);
1826 self.recover_arg_parse()?
1831 let span = lo.to(self.token.span);
1834 attrs: attrs.into(),
1835 id: ast::DUMMY_NODE_ID,
1836 is_placeholder: false,
1843 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1844 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1845 // Extract an identifier *after* having confirmed that the token is one.
1846 let expect_self_ident = |this: &mut Self| {
1847 match this.token.kind {
1848 // Preserve hygienic context.
1849 token::Ident(name, _) => {
1850 let span = this.token.span;
1852 Ident::new(name, span)
1854 _ => unreachable!(),
1857 // Is `self` `n` tokens ahead?
1858 let is_isolated_self = |this: &Self, n| {
1859 this.is_keyword_ahead(n, &[kw::SelfLower])
1860 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1862 // Is `mut self` `n` tokens ahead?
1863 let is_isolated_mut_self =
1864 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1865 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1866 let parse_self_possibly_typed = |this: &mut Self, m| {
1867 let eself_ident = expect_self_ident(this);
1868 let eself_hi = this.prev_span;
1869 let eself = if this.eat(&token::Colon) {
1870 SelfKind::Explicit(this.parse_ty()?, m)
1874 Ok((eself, eself_ident, eself_hi))
1876 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1877 let recover_self_ptr = |this: &mut Self| {
1878 let msg = "cannot pass `self` by raw pointer";
1879 let span = this.token.span;
1880 this.struct_span_err(span, msg).span_label(span, msg).emit();
1882 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1885 // Parse optional `self` parameter of a method.
1886 // Only a limited set of initial token sequences is considered `self` parameters; anything
1887 // else is parsed as a normal function parameter list, so some lookahead is required.
1888 let eself_lo = self.token.span;
1889 let (eself, eself_ident, eself_hi) = match self.token.kind {
1890 token::BinOp(token::And) => {
1891 let eself = if is_isolated_self(self, 1) {
1894 SelfKind::Region(None, Mutability::Not)
1895 } else if is_isolated_mut_self(self, 1) {
1899 SelfKind::Region(None, Mutability::Mut)
1900 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1903 let lt = self.expect_lifetime();
1904 SelfKind::Region(Some(lt), Mutability::Not)
1905 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1908 let lt = self.expect_lifetime();
1910 SelfKind::Region(Some(lt), Mutability::Mut)
1915 (eself, expect_self_ident(self), self.prev_span)
1918 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1920 recover_self_ptr(self)?
1922 // `*mut self` and `*const self`
1923 token::BinOp(token::Star)
1924 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1928 recover_self_ptr(self)?
1930 // `self` and `self: TYPE`
1931 token::Ident(..) if is_isolated_self(self, 0) => {
1932 parse_self_possibly_typed(self, Mutability::Not)?
1934 // `mut self` and `mut self: TYPE`
1935 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1937 parse_self_possibly_typed(self, Mutability::Mut)?
1939 _ => return Ok(None),
1942 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1943 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1946 fn is_named_param(&self) -> bool {
1947 let offset = match self.token.kind {
1948 token::Interpolated(ref nt) => match **nt {
1949 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1952 token::BinOp(token::And) | token::AndAnd => 1,
1953 _ if self.token.is_keyword(kw::Mut) => 1,
1957 self.look_ahead(offset, |t| t.is_ident())
1958 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1961 fn recover_first_param(&mut self) -> &'static str {
1963 .parse_outer_attributes()
1964 .and_then(|_| self.parse_self_param())
1965 .map_err(|mut e| e.cancel())
1967 Ok(Some(_)) => "method",