1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath};
3 use super::{FollowedByType, Parser, PathStyle};
5 use crate::maybe_whole;
7 use rustc_ast_pretty::pprust;
8 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, PResult, StashKey};
9 use rustc_span::source_map::{self, Span};
10 use rustc_span::symbol::{kw, sym, Symbol};
11 use rustc_span::BytePos;
12 use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
13 use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind};
14 use syntax::ast::{Async, Const, Defaultness, IsAuto, PathSegment, StrLit, Unsafe};
15 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
16 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
17 use syntax::ast::{FnHeader, ForeignItem, ForeignItemKind, Mutability, Visibility, VisibilityKind};
20 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
25 pub(super) type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
28 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
29 let attrs = self.parse_outer_attributes()?;
30 self.parse_item_(attrs, true, false)
33 pub(super) fn parse_item_(
35 attrs: Vec<Attribute>,
37 attributes_allowed: bool,
38 ) -> PResult<'a, Option<P<Item>>> {
39 let mut unclosed_delims = vec![];
40 let (ret, tokens) = self.collect_tokens(|this| {
41 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
42 unclosed_delims.append(&mut this.unclosed_delims);
45 self.unclosed_delims.append(&mut unclosed_delims);
47 // Once we've parsed an item and recorded the tokens we got while
48 // parsing we may want to store `tokens` into the item we're about to
49 // return. Note, though, that we specifically didn't capture tokens
50 // related to outer attributes. The `tokens` field here may later be
51 // used with procedural macros to convert this item back into a token
52 // stream, but during expansion we may be removing attributes as we go
55 // If we've got inner attributes then the `tokens` we've got above holds
56 // these inner attributes. If an inner attribute is expanded we won't
57 // actually remove it from the token stream, so we'll just keep yielding
58 // it (bad!). To work around this case for now we just avoid recording
59 // `tokens` if we detect any inner attributes. This should help keep
60 // expansion correct, but we should fix this bug one day!
63 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
64 i.tokens = Some(tokens);
71 /// Parses one of the items allowed by the flags.
72 fn parse_item_implementation(
74 mut attrs: Vec<Attribute>,
76 attributes_allowed: bool,
77 ) -> PResult<'a, Option<P<Item>>> {
78 maybe_whole!(self, NtItem, |item| {
80 mem::swap(&mut item.attrs, &mut attrs);
81 item.attrs.extend(attrs);
85 let lo = self.token.span;
87 let vis = self.parse_visibility(FollowedByType::No)?;
89 if self.eat_keyword(kw::Use) {
91 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
94 let span = lo.to(self.prev_span);
95 let item = self.mk_item(span, Ident::invalid(), item_, vis, attrs);
96 return Ok(Some(item));
99 if self.check_fn_front_matter() {
101 let (ident, sig, generics, body) = self.parse_fn(&mut false, &mut attrs, |_| true)?;
102 let kind = ItemKind::Fn(sig, generics, body);
103 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
106 if self.eat_keyword(kw::Extern) {
107 if self.eat_keyword(kw::Crate) {
109 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
112 let abi = self.parse_abi();
113 return Ok(Some(self.parse_item_foreign_mod(lo, abi, vis, attrs)?));
116 if self.is_static_global() {
119 let m = self.parse_mutability();
120 let info = self.parse_item_const(Some(m))?;
121 return self.mk_item_with_info(attrs, lo, vis, info);
124 if let Const::Yes(const_span) = self.parse_constness() {
126 if self.eat_keyword(kw::Mut) {
127 let prev_span = self.prev_span;
128 self.struct_span_err(prev_span, "const globals cannot be mutable")
129 .span_label(prev_span, "cannot be mutable")
132 "you might want to declare a static instead",
134 Applicability::MaybeIncorrect,
139 let info = self.parse_item_const(None)?;
140 return self.mk_item_with_info(attrs, lo, vis, info);
143 if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) {
145 let unsafety = self.parse_unsafety();
146 let info = self.parse_item_trait(lo, unsafety)?;
147 return self.mk_item_with_info(attrs, lo, vis, info);
150 if self.check_keyword(kw::Impl)
151 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
152 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
155 let defaultness = self.parse_defaultness();
156 let unsafety = self.parse_unsafety();
157 self.expect_keyword(kw::Impl)?;
158 let info = self.parse_item_impl(unsafety, defaultness)?;
159 return self.mk_item_with_info(attrs, lo, vis, info);
162 if self.eat_keyword(kw::Mod) {
164 let info = self.parse_item_mod(&attrs[..])?;
165 return self.mk_item_with_info(attrs, lo, vis, info);
168 if self.eat_keyword(kw::Type) {
170 let (ident, ty, generics) = self.parse_type_alias()?;
171 let kind = ItemKind::TyAlias(ty, generics);
172 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
175 if self.eat_keyword(kw::Enum) {
177 let info = self.parse_item_enum()?;
178 return self.mk_item_with_info(attrs, lo, vis, info);
181 if self.check_keyword(kw::Trait)
182 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
185 let info = self.parse_item_trait(lo, Unsafe::No)?;
186 return self.mk_item_with_info(attrs, lo, vis, info);
189 if self.eat_keyword(kw::Struct) {
191 let info = self.parse_item_struct()?;
192 return self.mk_item_with_info(attrs, lo, vis, info);
195 if self.is_union_item() {
198 let info = self.parse_item_union()?;
199 return self.mk_item_with_info(attrs, lo, vis, info);
202 if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? {
203 return Ok(Some(macro_def));
206 // Verify whether we have encountered a struct or method definition where the user forgot to
207 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
208 if vis.node.is_pub() && self.check_ident() && self.look_ahead(1, |t| *t != token::Not) {
209 // Space between `pub` keyword and the identifier
212 // ^^^ `sp` points here
213 let sp = self.prev_span.between(self.token.span);
214 let full_sp = self.prev_span.to(self.token.span);
215 let ident_sp = self.token.span;
216 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
217 // possible public struct definition where `struct` was forgotten
218 let ident = self.parse_ident().unwrap();
219 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
220 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
221 err.span_suggestion_short(
225 Applicability::MaybeIncorrect, // speculative
228 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
229 let ident = self.parse_ident().unwrap();
231 let kw_name = self.recover_first_param();
232 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
233 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
234 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
236 ("fn", kw_name, false)
237 } else if self.check(&token::OpenDelim(token::Brace)) {
239 ("fn", kw_name, false)
240 } else if self.check(&token::Colon) {
244 ("fn` or `struct", "function or struct", true)
247 let msg = format!("missing `{}` for {} definition", kw, kw_name);
248 let mut err = self.struct_span_err(sp, &msg);
250 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
252 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
253 err.span_suggestion_short(
257 Applicability::MachineApplicable,
260 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
263 "if you meant to call a macro, try",
264 format!("{}!", snippet),
265 // this is the `ambiguous` conditional branch
266 Applicability::MaybeIncorrect,
270 "if you meant to call a macro, remove the `pub` \
271 and add a trailing `!` after the identifier",
276 } else if self.look_ahead(1, |t| *t == token::Lt) {
277 let ident = self.parse_ident().unwrap();
278 self.eat_to_tokens(&[&token::Gt]);
280 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
281 ("fn", self.recover_first_param(), false)
282 } else if self.check(&token::OpenDelim(token::Brace)) {
283 ("struct", "struct", false)
285 ("fn` or `struct", "function or struct", true)
287 let msg = format!("missing `{}` for {} definition", kw, kw_name);
288 let mut err = self.struct_span_err(sp, &msg);
290 err.span_suggestion_short(
292 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
294 Applicability::MachineApplicable,
300 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis)
303 pub(super) fn mk_item_with_info(
305 attrs: Vec<Attribute>,
309 ) -> PResult<'a, Option<P<Item>>> {
310 let (ident, item, extra_attrs) = info;
311 let span = lo.to(self.prev_span);
312 let attrs = Self::maybe_append(attrs, extra_attrs);
313 Ok(Some(self.mk_item(span, ident, item, vis, attrs)))
316 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
317 if let Some(ref mut rhs) = rhs {
323 /// This is the fall-through for parsing items.
324 fn parse_macro_use_or_failure(
326 attrs: Vec<Attribute>,
327 macros_allowed: bool,
328 attributes_allowed: bool,
330 visibility: Visibility,
331 ) -> PResult<'a, Option<P<Item>>> {
333 && self.token.is_path_start()
334 && !(self.is_async_fn() && self.token.span.rust_2015())
336 // MACRO INVOCATION ITEM
338 let prev_span = self.prev_span;
339 self.complain_if_pub_macro(&visibility.node, prev_span);
342 let path = self.parse_path(PathStyle::Mod)?;
343 self.expect(&token::Not)?;
344 let args = self.parse_mac_args()?;
345 if args.need_semicolon() && !self.eat(&token::Semi) {
346 self.report_invalid_macro_expansion_item();
349 let hi = self.prev_span;
350 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
352 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
353 return Ok(Some(item));
356 // FAILURE TO PARSE ITEM
357 match visibility.node {
358 VisibilityKind::Inherited => {}
359 _ => return Err(self.struct_span_err(self.prev_span, "unmatched visibility `pub`")),
362 if !attributes_allowed && !attrs.is_empty() {
363 self.expected_item_err(&attrs)?;
368 /// Emits an expected-item-after-attributes error.
369 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
370 let message = match attrs.last() {
371 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
372 "expected item after doc comment"
374 _ => "expected item after attributes",
377 let mut err = self.struct_span_err(self.prev_span, message);
378 if attrs.last().unwrap().is_doc_comment() {
379 err.span_label(self.prev_span, "this doc comment doesn't document anything");
384 pub(super) fn is_async_fn(&self) -> bool {
385 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
388 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
389 fn parse_assoc_macro_invoc(
392 vis: Option<&Visibility>,
394 ) -> PResult<'a, Option<Mac>> {
395 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
396 let prev_span = self.prev_span;
397 let path = self.parse_path(PathStyle::Mod)?;
399 if path.segments.len() == 1 {
400 if !self.eat(&token::Not) {
401 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
404 self.expect(&token::Not)?;
407 if let Some(vis) = vis {
408 self.complain_if_pub_macro(&vis.node, prev_span);
413 // eat a matched-delimiter token tree:
414 let args = self.parse_mac_args()?;
415 if args.need_semicolon() {
419 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
425 fn missing_assoc_item_kind_err(
429 ) -> DiagnosticBuilder<'a> {
430 let expected_kinds = if item_type == "extern" {
431 "missing `fn`, `type`, or `static`"
433 "missing `fn`, `type`, or `const`"
436 // Given this code `path(`, it seems like this is not
437 // setting the visibility of a macro invocation, but rather
438 // a mistyped method declaration.
439 // Create a diagnostic pointing out that `fn` is missing.
441 // x | pub path(&self) {
442 // | ^ missing `fn`, `type`, or `const`
444 // ^^ `sp` below will point to this
445 let sp = prev_span.between(self.prev_span);
447 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
448 err.span_label(sp, expected_kinds);
452 /// Parses an implementation item, `impl` keyword is already parsed.
454 /// impl<'a, T> TYPE { /* impl items */ }
455 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
456 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
457 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
459 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
460 /// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
461 /// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
465 defaultness: Defaultness,
466 ) -> PResult<'a, ItemInfo> {
467 // First, parse generic parameters if necessary.
468 let mut generics = if self.choose_generics_over_qpath() {
469 self.parse_generics()?
471 let mut generics = Generics::default();
473 // /\ this is where `generics.span` should point when there are no type params.
474 generics.span = self.prev_span.shrink_to_hi();
478 let constness = self.parse_constness();
479 if let Const::Yes(span) = constness {
480 self.sess.gated_spans.gate(sym::const_trait_impl, span);
483 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
484 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
486 ast::ImplPolarity::Negative
488 ast::ImplPolarity::Positive
491 // Parse both types and traits as a type, then reinterpret if necessary.
492 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
493 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
495 let span = self.prev_span.between(self.token.span);
496 self.struct_span_err(span, "missing trait in a trait impl").emit();
497 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
502 // If `for` is missing we try to recover.
503 let has_for = self.eat_keyword(kw::For);
504 let missing_for_span = self.prev_span.between(self.token.span);
506 let ty_second = if self.token == token::DotDot {
507 // We need to report this error after `cfg` expansion for compatibility reasons
508 self.bump(); // `..`, do not add it to expected tokens
509 Some(self.mk_ty(self.prev_span, TyKind::Err))
510 } else if has_for || self.token.can_begin_type() {
511 Some(self.parse_ty()?)
516 generics.where_clause = self.parse_where_clause()?;
518 let (impl_items, attrs) = self.parse_impl_body()?;
520 let item_kind = match ty_second {
522 // impl Trait for Type
524 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
525 .span_suggestion_short(
529 Applicability::MachineApplicable,
534 let ty_first = ty_first.into_inner();
535 let path = match ty_first.kind {
536 // This notably includes paths passed through `ty` macro fragments (#46438).
537 TyKind::Path(None, path) => path,
539 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
540 err_path(ty_first.span)
543 let trait_ref = TraitRef { path, ref_id: ty_first.id };
551 of_trait: Some(trait_ref),
571 Ok((Ident::invalid(), item_kind, Some(attrs)))
574 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<P<AssocItem>>, Vec<Attribute>)> {
575 self.expect(&token::OpenDelim(token::Brace))?;
576 let attrs = self.parse_inner_attributes()?;
578 let mut impl_items = Vec::new();
579 while !self.eat(&token::CloseDelim(token::Brace)) {
580 let mut at_end = false;
581 match self.parse_impl_item(&mut at_end) {
582 Ok(impl_item) => impl_items.push(impl_item),
586 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
592 Ok((impl_items, attrs))
595 /// Parses defaultness (i.e., `default` or nothing).
596 fn parse_defaultness(&mut self) -> Defaultness {
597 // `pub` is included for better error messages
598 if self.check_keyword(kw::Default)
599 && self.is_keyword_ahead(
613 self.bump(); // `default`
620 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
621 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafe) -> PResult<'a, ItemInfo> {
622 // Parse optional `auto` prefix.
623 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
625 self.expect_keyword(kw::Trait)?;
626 let ident = self.parse_ident()?;
627 let mut tps = self.parse_generics()?;
629 // Parse optional colon and supertrait bounds.
630 let had_colon = self.eat(&token::Colon);
631 let span_at_colon = self.prev_span;
633 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
635 let span_before_eq = self.prev_span;
636 if self.eat(&token::Eq) {
637 // It's a trait alias.
639 let span = span_at_colon.to(span_before_eq);
640 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
643 let bounds = self.parse_generic_bounds(None)?;
644 tps.where_clause = self.parse_where_clause()?;
647 let whole_span = lo.to(self.prev_span);
648 if is_auto == IsAuto::Yes {
649 let msg = "trait aliases cannot be `auto`";
650 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
652 if let Unsafe::Yes(_) = unsafety {
653 let msg = "trait aliases cannot be `unsafe`";
654 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
657 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
659 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
661 // It's a normal trait.
662 tps.where_clause = self.parse_where_clause()?;
663 self.expect(&token::OpenDelim(token::Brace))?;
664 let mut trait_items = vec![];
665 while !self.eat(&token::CloseDelim(token::Brace)) {
666 if let token::DocComment(_) = self.token.kind {
667 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
672 "found a documentation comment that doesn't document anything",
675 "doc comments must come before what they document, maybe a \
676 comment was intended with `//`?",
683 let mut at_end = false;
684 match self.parse_trait_item(&mut at_end) {
685 Ok(item) => trait_items.push(item),
689 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
695 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
699 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
700 maybe_whole!(self, NtImplItem, |x| x);
701 self.parse_assoc_item(at_end, |_| true)
704 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
705 maybe_whole!(self, NtTraitItem, |x| x);
706 // This is somewhat dubious; We don't want to allow
707 // param names to be left off if there is a definition...
709 // We don't allow param names to be left off in edition 2018.
710 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
713 /// Parses associated items.
717 req_name: fn(&token::Token) -> bool,
718 ) -> PResult<'a, P<AssocItem>> {
719 let attrs = self.parse_outer_attributes()?;
720 let mut unclosed_delims = vec![];
721 let (mut item, tokens) = self.collect_tokens(|this| {
722 let item = this.parse_assoc_item_(at_end, attrs, req_name);
723 unclosed_delims.append(&mut this.unclosed_delims);
726 self.unclosed_delims.append(&mut unclosed_delims);
727 // See `parse_item` for why this clause is here.
728 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
729 item.tokens = Some(tokens);
734 fn parse_assoc_item_(
737 mut attrs: Vec<Attribute>,
738 req_name: fn(&token::Token) -> bool,
739 ) -> PResult<'a, AssocItem> {
740 let lo = self.token.span;
741 let vis = self.parse_visibility(FollowedByType::No)?;
742 let defaultness = self.parse_defaultness();
744 let (ident, kind, generics) = if self.eat_keyword(kw::Type) {
745 self.parse_assoc_ty()?
746 } else if self.check_fn_front_matter() {
747 let (ident, sig, generics, body) = self.parse_fn(at_end, &mut attrs, req_name)?;
748 (ident, AssocItemKind::Fn(sig, body), generics)
749 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
750 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
752 self.parse_assoc_const()?
755 let span = lo.to(self.prev_span);
756 let id = DUMMY_NODE_ID;
757 Ok(AssocItem { id, span, ident, attrs, vis, defaultness, generics, kind, tokens: None })
760 /// This parses the grammar:
762 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
763 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
764 self.expect_keyword(kw::Const)?;
765 let ident = self.parse_ident()?;
766 self.expect(&token::Colon)?;
767 let ty = self.parse_ty()?;
768 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
770 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
773 /// Parses the following grammar:
775 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
776 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
777 let ident = self.parse_ident()?;
778 let mut generics = self.parse_generics()?;
780 // Parse optional colon and param bounds.
782 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
783 generics.where_clause = self.parse_where_clause()?;
785 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
788 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
791 /// Parses a `UseTree`.
794 /// USE_TREE = [`::`] `*` |
795 /// [`::`] `{` USE_TREE_LIST `}` |
797 /// PATH `::` `{` USE_TREE_LIST `}` |
798 /// PATH [`as` IDENT]
800 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
801 let lo = self.token.span;
803 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
804 let kind = if self.check(&token::OpenDelim(token::Brace))
805 || self.check(&token::BinOp(token::Star))
806 || self.is_import_coupler()
808 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
809 let mod_sep_ctxt = self.token.span.ctxt();
810 if self.eat(&token::ModSep) {
813 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
816 self.parse_use_tree_glob_or_nested()?
818 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
819 prefix = self.parse_path(PathStyle::Mod)?;
821 if self.eat(&token::ModSep) {
822 self.parse_use_tree_glob_or_nested()?
824 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
828 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
831 /// Parses `*` or `{...}`.
832 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
833 Ok(if self.eat(&token::BinOp(token::Star)) {
836 UseTreeKind::Nested(self.parse_use_tree_list()?)
840 /// Parses a `UseTreeKind::Nested(list)`.
843 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
845 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
846 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
850 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
851 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
854 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
855 match self.token.kind {
856 token::Ident(name, false) if name == kw::Underscore => {
857 let span = self.token.span;
859 Ok(Ident::new(name, span))
861 _ => self.parse_ident(),
865 /// Parses `extern crate` links.
870 /// extern crate foo;
871 /// extern crate bar as foo;
873 fn parse_item_extern_crate(
876 visibility: Visibility,
877 attrs: Vec<Attribute>,
878 ) -> PResult<'a, P<Item>> {
879 // Accept `extern crate name-like-this` for better diagnostics
880 let orig_name = self.parse_crate_name_with_dashes()?;
881 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
882 (rename, Some(orig_name.name))
888 let span = lo.to(self.prev_span);
889 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
892 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
893 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
894 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
896 let mut ident = if self.token.is_keyword(kw::SelfLower) {
897 self.parse_path_segment_ident()
901 let mut idents = vec![];
902 let mut replacement = vec![];
903 let mut fixed_crate_name = false;
904 // Accept `extern crate name-like-this` for better diagnostics.
905 let dash = token::BinOp(token::BinOpToken::Minus);
906 if self.token == dash {
907 // Do not include `-` as part of the expected tokens list.
908 while self.eat(&dash) {
909 fixed_crate_name = true;
910 replacement.push((self.prev_span, "_".to_string()));
911 idents.push(self.parse_ident()?);
914 if fixed_crate_name {
915 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
916 let mut fixed_name = format!("{}", ident.name);
918 fixed_name.push_str(&format!("_{}", part.name));
920 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
922 self.struct_span_err(fixed_name_sp, error_msg)
923 .span_label(fixed_name_sp, "dash-separated idents are not valid")
924 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
930 /// Parses `extern` for foreign ABIs modules.
932 /// `extern` is expected to have been
933 /// consumed before calling this method.
937 /// ```ignore (only-for-syntax-highlight)
941 fn parse_item_foreign_mod(
945 visibility: Visibility,
946 mut attrs: Vec<Attribute>,
947 ) -> PResult<'a, P<Item>> {
948 self.expect(&token::OpenDelim(token::Brace))?;
950 attrs.extend(self.parse_inner_attributes()?);
952 let mut foreign_items = vec![];
953 while !self.eat(&token::CloseDelim(token::Brace)) {
954 foreign_items.push(self.parse_foreign_item()?);
957 let prev_span = self.prev_span;
958 let m = ast::ForeignMod { abi, items: foreign_items };
959 let invalid = Ident::invalid();
960 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
963 /// Parses a foreign item (one in an `extern { ... }` block).
964 pub fn parse_foreign_item(&mut self) -> PResult<'a, P<ForeignItem>> {
965 maybe_whole!(self, NtForeignItem, |ni| ni);
967 let mut attrs = self.parse_outer_attributes()?;
968 let lo = self.token.span;
969 let vis = self.parse_visibility(FollowedByType::No)?;
971 let (ident, kind) = if self.check_keyword(kw::Type) {
973 self.parse_item_foreign_type()?
974 } else if self.check_fn_front_matter() {
975 // FOREIGN FUNCTION ITEM
976 let (ident, sig, generics, body) = self.parse_fn(&mut false, &mut attrs, |_| true)?;
977 (ident, ForeignItemKind::Fn(sig, generics, body))
978 } else if self.is_static_global() {
979 // FOREIGN STATIC ITEM
980 self.bump(); // `static`
981 self.parse_item_foreign_static()?
982 } else if self.token.is_keyword(kw::Const) {
983 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
984 self.bump(); // `const`
985 self.struct_span_err(self.prev_span, "extern items cannot be `const`")
988 "try using a static value",
990 Applicability::MachineApplicable,
993 self.parse_item_foreign_static()?
994 } else if let Some(mac) = self.parse_assoc_macro_invoc("extern", Some(&vis), &mut false)? {
995 (Ident::invalid(), ForeignItemKind::Macro(mac))
997 if !attrs.is_empty() {
998 self.expected_item_err(&attrs)?;
1003 let span = lo.to(self.prev_span);
1004 Ok(P(ast::ForeignItem { ident, attrs, kind, id: DUMMY_NODE_ID, span, vis, tokens: None }))
1007 /// Parses a static item from a foreign module.
1008 /// Assumes that the `static` keyword is already parsed.
1009 fn parse_item_foreign_static(&mut self) -> PResult<'a, (Ident, ForeignItemKind)> {
1010 let mutbl = self.parse_mutability();
1011 let ident = self.parse_ident()?;
1012 self.expect(&token::Colon)?;
1013 let ty = self.parse_ty()?;
1014 self.expect_semi()?;
1015 Ok((ident, ForeignItemKind::Static(ty, mutbl)))
1018 /// Parses a type from a foreign module.
1019 fn parse_item_foreign_type(&mut self) -> PResult<'a, (Ident, ForeignItemKind)> {
1020 self.expect_keyword(kw::Type)?;
1021 let ident = self.parse_ident()?;
1022 self.expect_semi()?;
1023 Ok((ident, ForeignItemKind::Ty))
1026 fn is_static_global(&mut self) -> bool {
1027 if self.check_keyword(kw::Static) {
1028 // Check if this could be a closure.
1029 !self.look_ahead(1, |token| {
1030 if token.is_keyword(kw::Move) {
1034 token::BinOp(token::Or) | token::OrOr => true,
1043 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1044 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1046 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1047 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1048 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1050 // Parse the type of a `const` or `static mut?` item.
1051 // That is, the `":" $ty` fragment.
1052 let ty = if self.token == token::Eq {
1053 self.recover_missing_const_type(id, m)
1055 // Not `=` so expect `":"" $ty` as usual.
1056 self.expect(&token::Colon)?;
1060 self.expect(&token::Eq)?;
1061 let e = self.parse_expr()?;
1062 self.expect_semi()?;
1063 let item = match m {
1064 Some(m) => ItemKind::Static(ty, m, e),
1065 None => ItemKind::Const(ty, e),
1067 Ok((id, item, None))
1070 /// We were supposed to parse `:` but instead, we're already at `=`.
1071 /// This means that the type is missing.
1072 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1073 // Construct the error and stash it away with the hope
1074 // that typeck will later enrich the error with a type.
1075 let kind = match m {
1076 Some(Mutability::Mut) => "static mut",
1077 Some(Mutability::Not) => "static",
1080 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1081 err.span_suggestion(
1083 "provide a type for the item",
1084 format!("{}: <type>", id),
1085 Applicability::HasPlaceholders,
1087 err.stash(id.span, StashKey::ItemNoType);
1089 // The user intended that the type be inferred,
1090 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1091 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1094 /// Parses the grammar:
1095 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1096 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1097 let ident = self.parse_ident()?;
1098 let mut tps = self.parse_generics()?;
1099 tps.where_clause = self.parse_where_clause()?;
1100 self.expect(&token::Eq)?;
1101 let ty = self.parse_ty()?;
1102 self.expect_semi()?;
1103 Ok((ident, ty, tps))
1106 /// Parses an enum declaration.
1107 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1108 let id = self.parse_ident()?;
1109 let mut generics = self.parse_generics()?;
1110 generics.where_clause = self.parse_where_clause()?;
1113 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1114 self.recover_stmt();
1118 let enum_definition =
1119 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1120 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1123 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1124 let variant_attrs = self.parse_outer_attributes()?;
1125 let vlo = self.token.span;
1127 let vis = self.parse_visibility(FollowedByType::No)?;
1128 if !self.recover_nested_adt_item(kw::Enum)? {
1131 let ident = self.parse_ident()?;
1133 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1134 // Parse a struct variant.
1135 let (fields, recovered) = self.parse_record_struct_body()?;
1136 VariantData::Struct(fields, recovered)
1137 } else if self.check(&token::OpenDelim(token::Paren)) {
1138 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1140 VariantData::Unit(DUMMY_NODE_ID)
1144 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1146 let vr = ast::Variant {
1150 attrs: variant_attrs,
1153 span: vlo.to(self.prev_span),
1154 is_placeholder: false,
1160 /// Parses `struct Foo { ... }`.
1161 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1162 let class_name = self.parse_ident()?;
1164 let mut generics = self.parse_generics()?;
1166 // There is a special case worth noting here, as reported in issue #17904.
1167 // If we are parsing a tuple struct it is the case that the where clause
1168 // should follow the field list. Like so:
1170 // struct Foo<T>(T) where T: Copy;
1172 // If we are parsing a normal record-style struct it is the case
1173 // that the where clause comes before the body, and after the generics.
1174 // So if we look ahead and see a brace or a where-clause we begin
1175 // parsing a record style struct.
1177 // Otherwise if we look ahead and see a paren we parse a tuple-style
1180 let vdata = if self.token.is_keyword(kw::Where) {
1181 generics.where_clause = self.parse_where_clause()?;
1182 if self.eat(&token::Semi) {
1183 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1184 VariantData::Unit(DUMMY_NODE_ID)
1186 // If we see: `struct Foo<T> where T: Copy { ... }`
1187 let (fields, recovered) = self.parse_record_struct_body()?;
1188 VariantData::Struct(fields, recovered)
1190 // No `where` so: `struct Foo<T>;`
1191 } else if self.eat(&token::Semi) {
1192 VariantData::Unit(DUMMY_NODE_ID)
1193 // Record-style struct definition
1194 } else if self.token == token::OpenDelim(token::Brace) {
1195 let (fields, recovered) = self.parse_record_struct_body()?;
1196 VariantData::Struct(fields, recovered)
1197 // Tuple-style struct definition with optional where-clause.
1198 } else if self.token == token::OpenDelim(token::Paren) {
1199 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1200 generics.where_clause = self.parse_where_clause()?;
1201 self.expect_semi()?;
1204 let token_str = super::token_descr(&self.token);
1206 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1209 let mut err = self.struct_span_err(self.token.span, msg);
1210 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1214 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1217 /// Parses `union Foo { ... }`.
1218 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1219 let class_name = self.parse_ident()?;
1221 let mut generics = self.parse_generics()?;
1223 let vdata = if self.token.is_keyword(kw::Where) {
1224 generics.where_clause = self.parse_where_clause()?;
1225 let (fields, recovered) = self.parse_record_struct_body()?;
1226 VariantData::Struct(fields, recovered)
1227 } else if self.token == token::OpenDelim(token::Brace) {
1228 let (fields, recovered) = self.parse_record_struct_body()?;
1229 VariantData::Struct(fields, recovered)
1231 let token_str = super::token_descr(&self.token);
1232 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1233 let mut err = self.struct_span_err(self.token.span, msg);
1234 err.span_label(self.token.span, "expected `where` or `{` after union name");
1238 Ok((class_name, ItemKind::Union(vdata, generics), None))
1241 pub(super) fn is_union_item(&self) -> bool {
1242 self.token.is_keyword(kw::Union)
1243 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1246 fn parse_record_struct_body(
1248 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1249 let mut fields = Vec::new();
1250 let mut recovered = false;
1251 if self.eat(&token::OpenDelim(token::Brace)) {
1252 while self.token != token::CloseDelim(token::Brace) {
1253 let field = self.parse_struct_decl_field().map_err(|e| {
1254 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1259 Ok(field) => fields.push(field),
1266 self.eat(&token::CloseDelim(token::Brace));
1268 let token_str = super::token_descr(&self.token);
1269 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1270 let mut err = self.struct_span_err(self.token.span, msg);
1271 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1275 Ok((fields, recovered))
1278 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1279 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1280 // Unit like structs are handled in parse_item_struct function
1281 self.parse_paren_comma_seq(|p| {
1282 let attrs = p.parse_outer_attributes()?;
1283 let lo = p.token.span;
1284 let vis = p.parse_visibility(FollowedByType::Yes)?;
1285 let ty = p.parse_ty()?;
1287 span: lo.to(ty.span),
1293 is_placeholder: false,
1299 /// Parses an element of a struct declaration.
1300 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1301 let attrs = self.parse_outer_attributes()?;
1302 let lo = self.token.span;
1303 let vis = self.parse_visibility(FollowedByType::No)?;
1304 self.parse_single_struct_field(lo, vis, attrs)
1307 /// Parses a structure field declaration.
1308 fn parse_single_struct_field(
1312 attrs: Vec<Attribute>,
1313 ) -> PResult<'a, StructField> {
1314 let mut seen_comma: bool = false;
1315 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1316 if self.token == token::Comma {
1319 match self.token.kind {
1323 token::CloseDelim(token::Brace) => {}
1324 token::DocComment(_) => {
1325 let previous_span = self.prev_span;
1326 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1327 self.bump(); // consume the doc comment
1328 let comma_after_doc_seen = self.eat(&token::Comma);
1329 // `seen_comma` is always false, because we are inside doc block
1330 // condition is here to make code more readable
1331 if seen_comma == false && comma_after_doc_seen == true {
1334 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1337 if seen_comma == false {
1338 let sp = self.sess.source_map().next_point(previous_span);
1339 err.span_suggestion(
1341 "missing comma here",
1343 Applicability::MachineApplicable,
1350 let sp = self.prev_span.shrink_to_hi();
1351 let mut err = self.struct_span_err(
1353 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1355 if self.token.is_ident() {
1356 // This is likely another field; emit the diagnostic and keep going
1357 err.span_suggestion(
1359 "try adding a comma",
1361 Applicability::MachineApplicable,
1372 /// Parses a structure field.
1373 fn parse_name_and_ty(
1377 attrs: Vec<Attribute>,
1378 ) -> PResult<'a, StructField> {
1379 let name = self.parse_ident()?;
1380 self.expect(&token::Colon)?;
1381 let ty = self.parse_ty()?;
1383 span: lo.to(self.prev_span),
1389 is_placeholder: false,
1393 pub(super) fn eat_macro_def(
1395 attrs: &[Attribute],
1398 ) -> PResult<'a, Option<P<Item>>> {
1399 let (ident, def) = if self.eat_keyword(kw::Macro) {
1400 let ident = self.parse_ident()?;
1401 let body = if self.check(&token::OpenDelim(token::Brace)) {
1402 self.parse_mac_args()?
1403 } else if self.check(&token::OpenDelim(token::Paren)) {
1404 let params = self.parse_token_tree();
1405 let pspan = params.span();
1406 let body = if self.check(&token::OpenDelim(token::Brace)) {
1407 self.parse_token_tree()
1409 return self.unexpected();
1411 let bspan = body.span();
1412 let tokens = TokenStream::new(vec![
1414 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1417 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1418 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1420 return self.unexpected();
1423 (ident, ast::MacroDef { body, legacy: false })
1424 } else if self.check_keyword(sym::macro_rules)
1425 && self.look_ahead(1, |t| *t == token::Not)
1426 && self.look_ahead(2, |t| t.is_ident())
1428 let prev_span = self.prev_span;
1429 self.complain_if_pub_macro(&vis.node, prev_span);
1433 let ident = self.parse_ident()?;
1434 let body = self.parse_mac_args()?;
1435 if body.need_semicolon() && !self.eat(&token::Semi) {
1436 self.report_invalid_macro_expansion_item();
1439 (ident, ast::MacroDef { body, legacy: true })
1444 let span = lo.to(self.prev_span);
1447 self.sess.gated_spans.gate(sym::decl_macro, span);
1450 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1453 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1455 VisibilityKind::Inherited => {}
1457 let mut err = if self.token.is_keyword(sym::macro_rules) {
1459 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1460 err.span_suggestion(
1462 "try exporting the macro",
1463 "#[macro_export]".to_owned(),
1464 Applicability::MaybeIncorrect, // speculative
1469 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1470 err.help("try adjusting the macro to put `pub` inside the invocation");
1478 fn report_invalid_macro_expansion_item(&self) {
1479 let has_close_delim = self
1482 .span_to_snippet(self.prev_span)
1483 .map(|s| s.ends_with(")") || s.ends_with("]"))
1486 let mut err = self.struct_span_err(
1488 "macros that expand to items must be delimited with braces or followed by a semicolon",
1491 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1492 if has_close_delim {
1493 err.multipart_suggestion(
1494 "change the delimiters to curly braces",
1496 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1497 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1499 Applicability::MaybeIncorrect,
1502 err.span_suggestion(
1504 "change the delimiters to curly braces",
1505 " { /* items */ }".to_string(),
1506 Applicability::HasPlaceholders,
1510 err.span_suggestion(
1511 self.prev_span.shrink_to_hi(),
1514 Applicability::MaybeIncorrect,
1519 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1520 /// it is, we try to parse the item and report error about nested types.
1521 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1522 if (self.token.is_keyword(kw::Enum)
1523 || self.token.is_keyword(kw::Struct)
1524 || self.token.is_keyword(kw::Union))
1525 && self.look_ahead(1, |t| t.is_ident())
1527 let kw_token = self.token.clone();
1528 let kw_str = pprust::token_to_string(&kw_token);
1529 let item = self.parse_item()?;
1531 self.struct_span_err(
1533 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1537 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1539 Applicability::MaybeIncorrect,
1542 // We successfully parsed the item but we must inform the caller about nested problem.
1554 attrs: Vec<Attribute>,
1556 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1560 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1562 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1563 type ReqName = fn(&token::Token) -> bool;
1565 /// Parsing of functions and methods.
1566 impl<'a> Parser<'a> {
1567 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1571 attrs: &mut Vec<Attribute>,
1573 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1574 let header = self.parse_fn_front_matter()?; // `const ... fn`
1575 let ident = self.parse_ident()?; // `foo`
1576 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1577 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1578 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1579 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1580 Ok((ident, FnSig { header, decl }, generics, body))
1583 /// Parse the "body" of a function.
1584 /// This can either be `;` when there's no body,
1585 /// or e.g. a block when the function is a provided one.
1589 attrs: &mut Vec<Attribute>,
1590 ) -> PResult<'a, Option<P<Block>>> {
1591 let (inner_attrs, body) = match self.token.kind {
1596 token::OpenDelim(token::Brace) => {
1597 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1600 token::Interpolated(ref nt) => match **nt {
1601 token::NtBlock(..) => {
1602 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1605 _ => return self.expected_semi_or_open_brace(),
1607 _ => return self.expected_semi_or_open_brace(),
1609 attrs.extend(inner_attrs);
1614 /// Is the current token the start of an `FnHeader` / not a valid parse?
1615 fn check_fn_front_matter(&mut self) -> bool {
1616 // We use an over-approximation here.
1617 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1618 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1619 self.check_keyword(kw::Fn) // Definitely an `fn`.
1620 // `$qual fn` or `$qual $qual`:
1621 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1622 && self.look_ahead(1, |t| {
1623 // ...qualified and then `fn`, e.g. `const fn`.
1624 t.is_keyword(kw::Fn)
1625 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1626 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1629 || self.check_keyword(kw::Extern)
1630 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1631 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1634 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1635 /// up to and including the `fn` keyword. The formal grammar is:
1638 /// Extern = "extern" StringLit ;
1639 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1640 /// FnFrontMatter = FnQual? "fn" ;
1642 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1643 let constness = self.parse_constness();
1644 let asyncness = self.parse_asyncness();
1645 let unsafety = self.parse_unsafety();
1646 let ext = self.parse_extern()?;
1648 if let Async::Yes { span, .. } = asyncness {
1649 self.ban_async_in_2015(span);
1652 if !self.eat_keyword(kw::Fn) {
1653 // It is possible for `expect_one_of` to recover given the contents of
1654 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1655 // account for this.
1656 if !self.expect_one_of(&[], &[])? {
1661 Ok(FnHeader { constness, unsafety, asyncness, ext })
1664 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1665 fn ban_async_in_2015(&self, span: Span) {
1666 if span.rust_2015() {
1667 let diag = self.diagnostic();
1668 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1669 .note("to use `async fn`, switch to Rust 2018")
1670 .help("set `edition = \"2018\"` in `Cargo.toml`")
1671 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1676 /// Parses the parameter list and result type of a function declaration.
1677 pub(super) fn parse_fn_decl(
1680 ret_allow_plus: AllowPlus,
1681 ) -> PResult<'a, P<FnDecl>> {
1683 inputs: self.parse_fn_params(req_name)?,
1684 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1688 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1689 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1690 let mut first_param = true;
1691 // Parse the arguments, starting out with `self` being allowed...
1692 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1693 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1695 let lo = p.prev_span;
1696 // Skip every token until next possible arg or end.
1697 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1698 // Create a placeholder argument for proper arg count (issue #34264).
1699 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1701 // ...now that we've parsed the first argument, `self` is no longer allowed.
1702 first_param = false;
1705 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1706 self.deduplicate_recovered_params_names(&mut params);
1710 /// Parses a single function parameter.
1712 /// - `self` is syntactically allowed when `first_param` holds.
1713 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1714 let lo = self.token.span;
1715 let attrs = self.parse_outer_attributes()?;
1717 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1718 if let Some(mut param) = self.parse_self_param()? {
1719 param.attrs = attrs.into();
1720 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1723 let is_name_required = match self.token.kind {
1724 token::DotDotDot => false,
1725 _ => req_name(&self.token),
1727 let (pat, ty) = if is_name_required || self.is_named_param() {
1728 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1730 let pat = self.parse_fn_param_pat()?;
1731 if let Err(mut err) = self.expect(&token::Colon) {
1732 return if let Some(ident) =
1733 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1736 Ok(dummy_arg(ident))
1742 self.eat_incorrect_doc_comment_for_param_type();
1743 (pat, self.parse_ty_for_param()?)
1745 debug!("parse_param_general ident_to_pat");
1746 let parser_snapshot_before_ty = self.clone();
1747 self.eat_incorrect_doc_comment_for_param_type();
1748 let mut ty = self.parse_ty_for_param();
1750 && self.token != token::Comma
1751 && self.token != token::CloseDelim(token::Paren)
1753 // This wasn't actually a type, but a pattern looking like a type,
1754 // so we are going to rollback and re-parse for recovery.
1755 ty = self.unexpected();
1759 let ident = Ident::new(kw::Invalid, self.prev_span);
1760 let bm = BindingMode::ByValue(Mutability::Not);
1761 let pat = self.mk_pat_ident(ty.span, bm, ident);
1764 // If this is a C-variadic argument and we hit an error, return the error.
1765 Err(err) if self.token == token::DotDotDot => return Err(err),
1766 // Recover from attempting to parse the argument as a type without pattern.
1769 mem::replace(self, parser_snapshot_before_ty);
1770 self.recover_arg_parse()?
1775 let span = lo.to(self.token.span);
1778 attrs: attrs.into(),
1779 id: ast::DUMMY_NODE_ID,
1780 is_placeholder: false,
1787 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1788 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1789 // Extract an identifier *after* having confirmed that the token is one.
1790 let expect_self_ident = |this: &mut Self| {
1791 match this.token.kind {
1792 // Preserve hygienic context.
1793 token::Ident(name, _) => {
1794 let span = this.token.span;
1796 Ident::new(name, span)
1798 _ => unreachable!(),
1801 // Is `self` `n` tokens ahead?
1802 let is_isolated_self = |this: &Self, n| {
1803 this.is_keyword_ahead(n, &[kw::SelfLower])
1804 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1806 // Is `mut self` `n` tokens ahead?
1807 let is_isolated_mut_self =
1808 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1809 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1810 let parse_self_possibly_typed = |this: &mut Self, m| {
1811 let eself_ident = expect_self_ident(this);
1812 let eself_hi = this.prev_span;
1813 let eself = if this.eat(&token::Colon) {
1814 SelfKind::Explicit(this.parse_ty()?, m)
1818 Ok((eself, eself_ident, eself_hi))
1820 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1821 let recover_self_ptr = |this: &mut Self| {
1822 let msg = "cannot pass `self` by raw pointer";
1823 let span = this.token.span;
1824 this.struct_span_err(span, msg).span_label(span, msg).emit();
1826 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1829 // Parse optional `self` parameter of a method.
1830 // Only a limited set of initial token sequences is considered `self` parameters; anything
1831 // else is parsed as a normal function parameter list, so some lookahead is required.
1832 let eself_lo = self.token.span;
1833 let (eself, eself_ident, eself_hi) = match self.token.kind {
1834 token::BinOp(token::And) => {
1835 let eself = if is_isolated_self(self, 1) {
1838 SelfKind::Region(None, Mutability::Not)
1839 } else if is_isolated_mut_self(self, 1) {
1843 SelfKind::Region(None, Mutability::Mut)
1844 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1847 let lt = self.expect_lifetime();
1848 SelfKind::Region(Some(lt), Mutability::Not)
1849 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1852 let lt = self.expect_lifetime();
1854 SelfKind::Region(Some(lt), Mutability::Mut)
1859 (eself, expect_self_ident(self), self.prev_span)
1862 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1864 recover_self_ptr(self)?
1866 // `*mut self` and `*const self`
1867 token::BinOp(token::Star)
1868 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1872 recover_self_ptr(self)?
1874 // `self` and `self: TYPE`
1875 token::Ident(..) if is_isolated_self(self, 0) => {
1876 parse_self_possibly_typed(self, Mutability::Not)?
1878 // `mut self` and `mut self: TYPE`
1879 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1881 parse_self_possibly_typed(self, Mutability::Mut)?
1883 _ => return Ok(None),
1886 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1887 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1890 fn is_named_param(&self) -> bool {
1891 let offset = match self.token.kind {
1892 token::Interpolated(ref nt) => match **nt {
1893 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1896 token::BinOp(token::And) | token::AndAnd => 1,
1897 _ if self.token.is_keyword(kw::Mut) => 1,
1901 self.look_ahead(offset, |t| t.is_ident())
1902 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1905 fn recover_first_param(&mut self) -> &'static str {
1907 .parse_outer_attributes()
1908 .and_then(|_| self.parse_self_param())
1909 .map_err(|mut e| e.cancel())
1911 Ok(Some(_)) => "method",