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 return self.parse_item_fn(lo, vis, attrs);
104 if self.eat_keyword(kw::Extern) {
105 if self.eat_keyword(kw::Crate) {
107 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
110 let abi = self.parse_abi();
111 return Ok(Some(self.parse_item_foreign_mod(lo, abi, vis, attrs)?));
114 if self.is_static_global() {
117 let m = self.parse_mutability();
118 let info = self.parse_item_const(Some(m))?;
119 return self.mk_item_with_info(attrs, lo, vis, info);
122 if let Const::Yes(const_span) = self.parse_constness() {
124 if self.eat_keyword(kw::Mut) {
125 let prev_span = self.prev_span;
126 self.struct_span_err(prev_span, "const globals cannot be mutable")
127 .span_label(prev_span, "cannot be mutable")
130 "you might want to declare a static instead",
132 Applicability::MaybeIncorrect,
137 let info = self.parse_item_const(None)?;
138 return self.mk_item_with_info(attrs, lo, vis, info);
141 if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) {
143 let unsafety = self.parse_unsafety();
144 let info = self.parse_item_trait(lo, unsafety)?;
145 return self.mk_item_with_info(attrs, lo, vis, info);
148 if self.check_keyword(kw::Impl)
149 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
150 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
153 let defaultness = self.parse_defaultness();
154 let unsafety = self.parse_unsafety();
155 self.expect_keyword(kw::Impl)?;
156 let info = self.parse_item_impl(unsafety, defaultness)?;
157 return self.mk_item_with_info(attrs, lo, vis, info);
160 if self.eat_keyword(kw::Mod) {
162 let info = self.parse_item_mod(&attrs[..])?;
163 return self.mk_item_with_info(attrs, lo, vis, info);
166 if self.eat_keyword(kw::Type) {
168 let (ident, ty, generics) = self.parse_type_alias()?;
169 let kind = ItemKind::TyAlias(ty, generics);
170 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
173 if self.eat_keyword(kw::Enum) {
175 let info = self.parse_item_enum()?;
176 return self.mk_item_with_info(attrs, lo, vis, info);
179 if self.check_keyword(kw::Trait)
180 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
183 let info = self.parse_item_trait(lo, Unsafe::No)?;
184 return self.mk_item_with_info(attrs, lo, vis, info);
187 if self.eat_keyword(kw::Struct) {
189 let info = self.parse_item_struct()?;
190 return self.mk_item_with_info(attrs, lo, vis, info);
193 if self.is_union_item() {
196 let info = self.parse_item_union()?;
197 return self.mk_item_with_info(attrs, lo, vis, info);
200 if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? {
201 return Ok(Some(macro_def));
204 // Verify whether we have encountered a struct or method definition where the user forgot to
205 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
206 if vis.node.is_pub() && self.check_ident() && self.look_ahead(1, |t| *t != token::Not) {
207 // Space between `pub` keyword and the identifier
210 // ^^^ `sp` points here
211 let sp = self.prev_span.between(self.token.span);
212 let full_sp = self.prev_span.to(self.token.span);
213 let ident_sp = self.token.span;
214 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
215 // possible public struct definition where `struct` was forgotten
216 let ident = self.parse_ident().unwrap();
217 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
218 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
219 err.span_suggestion_short(
223 Applicability::MaybeIncorrect, // speculative
226 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
227 let ident = self.parse_ident().unwrap();
229 let kw_name = self.recover_first_param();
230 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
231 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
232 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
234 ("fn", kw_name, false)
235 } else if self.check(&token::OpenDelim(token::Brace)) {
237 ("fn", kw_name, false)
238 } else if self.check(&token::Colon) {
242 ("fn` or `struct", "function or struct", true)
245 let msg = format!("missing `{}` for {} definition", kw, kw_name);
246 let mut err = self.struct_span_err(sp, &msg);
248 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
250 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
251 err.span_suggestion_short(
255 Applicability::MachineApplicable,
258 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
261 "if you meant to call a macro, try",
262 format!("{}!", snippet),
263 // this is the `ambiguous` conditional branch
264 Applicability::MaybeIncorrect,
268 "if you meant to call a macro, remove the `pub` \
269 and add a trailing `!` after the identifier",
274 } else if self.look_ahead(1, |t| *t == token::Lt) {
275 let ident = self.parse_ident().unwrap();
276 self.eat_to_tokens(&[&token::Gt]);
278 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
279 ("fn", self.recover_first_param(), false)
280 } else if self.check(&token::OpenDelim(token::Brace)) {
281 ("struct", "struct", false)
283 ("fn` or `struct", "function or struct", true)
285 let msg = format!("missing `{}` for {} definition", kw, kw_name);
286 let mut err = self.struct_span_err(sp, &msg);
288 err.span_suggestion_short(
290 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
292 Applicability::MachineApplicable,
298 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis)
301 pub(super) fn mk_item_with_info(
303 attrs: Vec<Attribute>,
307 ) -> PResult<'a, Option<P<Item>>> {
308 let (ident, item, extra_attrs) = info;
309 let span = lo.to(self.prev_span);
310 let attrs = Self::maybe_append(attrs, extra_attrs);
311 Ok(Some(self.mk_item(span, ident, item, vis, attrs)))
314 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
315 if let Some(ref mut rhs) = rhs {
321 /// This is the fall-through for parsing items.
322 fn parse_macro_use_or_failure(
324 attrs: Vec<Attribute>,
325 macros_allowed: bool,
326 attributes_allowed: bool,
328 visibility: Visibility,
329 ) -> PResult<'a, Option<P<Item>>> {
331 && self.token.is_path_start()
332 && !(self.is_async_fn() && self.token.span.rust_2015())
334 // MACRO INVOCATION ITEM
336 let prev_span = self.prev_span;
337 self.complain_if_pub_macro(&visibility.node, prev_span);
340 let path = self.parse_path(PathStyle::Mod)?;
341 self.expect(&token::Not)?;
342 let args = self.parse_mac_args()?;
343 if args.need_semicolon() && !self.eat(&token::Semi) {
344 self.report_invalid_macro_expansion_item();
347 let hi = self.prev_span;
348 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
350 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
351 return Ok(Some(item));
354 // FAILURE TO PARSE ITEM
355 match visibility.node {
356 VisibilityKind::Inherited => {}
357 _ => return Err(self.struct_span_err(self.prev_span, "unmatched visibility `pub`")),
360 if !attributes_allowed && !attrs.is_empty() {
361 self.expected_item_err(&attrs)?;
366 /// Emits an expected-item-after-attributes error.
367 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
368 let message = match attrs.last() {
369 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
370 "expected item after doc comment"
372 _ => "expected item after attributes",
375 let mut err = self.struct_span_err(self.prev_span, message);
376 if attrs.last().unwrap().is_doc_comment() {
377 err.span_label(self.prev_span, "this doc comment doesn't document anything");
382 pub(super) fn is_async_fn(&self) -> bool {
383 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
386 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
387 fn parse_assoc_macro_invoc(
390 vis: Option<&Visibility>,
392 ) -> PResult<'a, Option<Mac>> {
393 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
394 let prev_span = self.prev_span;
395 let path = self.parse_path(PathStyle::Mod)?;
397 if path.segments.len() == 1 {
398 if !self.eat(&token::Not) {
399 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
402 self.expect(&token::Not)?;
405 if let Some(vis) = vis {
406 self.complain_if_pub_macro(&vis.node, prev_span);
411 // eat a matched-delimiter token tree:
412 let args = self.parse_mac_args()?;
413 if args.need_semicolon() {
417 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
423 fn missing_assoc_item_kind_err(
427 ) -> DiagnosticBuilder<'a> {
428 let expected_kinds = if item_type == "extern" {
429 "missing `fn`, `type`, or `static`"
431 "missing `fn`, `type`, or `const`"
434 // Given this code `path(`, it seems like this is not
435 // setting the visibility of a macro invocation, but rather
436 // a mistyped method declaration.
437 // Create a diagnostic pointing out that `fn` is missing.
439 // x | pub path(&self) {
440 // | ^ missing `fn`, `type`, or `const`
442 // ^^ `sp` below will point to this
443 let sp = prev_span.between(self.prev_span);
445 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
446 err.span_label(sp, expected_kinds);
450 /// Parses an implementation item, `impl` keyword is already parsed.
452 /// impl<'a, T> TYPE { /* impl items */ }
453 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
454 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
455 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
457 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
458 /// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
459 /// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
463 defaultness: Defaultness,
464 ) -> PResult<'a, ItemInfo> {
465 // First, parse generic parameters if necessary.
466 let mut generics = if self.choose_generics_over_qpath() {
467 self.parse_generics()?
469 let mut generics = Generics::default();
471 // /\ this is where `generics.span` should point when there are no type params.
472 generics.span = self.prev_span.shrink_to_hi();
476 let constness = self.parse_constness();
477 if let Const::Yes(span) = constness {
478 self.sess.gated_spans.gate(sym::const_trait_impl, span);
481 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
482 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
484 ast::ImplPolarity::Negative
486 ast::ImplPolarity::Positive
489 // Parse both types and traits as a type, then reinterpret if necessary.
490 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
491 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
493 let span = self.prev_span.between(self.token.span);
494 self.struct_span_err(span, "missing trait in a trait impl").emit();
495 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
500 // If `for` is missing we try to recover.
501 let has_for = self.eat_keyword(kw::For);
502 let missing_for_span = self.prev_span.between(self.token.span);
504 let ty_second = if self.token == token::DotDot {
505 // We need to report this error after `cfg` expansion for compatibility reasons
506 self.bump(); // `..`, do not add it to expected tokens
507 Some(self.mk_ty(self.prev_span, TyKind::Err))
508 } else if has_for || self.token.can_begin_type() {
509 Some(self.parse_ty()?)
514 generics.where_clause = self.parse_where_clause()?;
516 let (impl_items, attrs) = self.parse_impl_body()?;
518 let item_kind = match ty_second {
520 // impl Trait for Type
522 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
523 .span_suggestion_short(
527 Applicability::MachineApplicable,
532 let ty_first = ty_first.into_inner();
533 let path = match ty_first.kind {
534 // This notably includes paths passed through `ty` macro fragments (#46438).
535 TyKind::Path(None, path) => path,
537 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
538 err_path(ty_first.span)
541 let trait_ref = TraitRef { path, ref_id: ty_first.id };
549 of_trait: Some(trait_ref),
569 Ok((Ident::invalid(), item_kind, Some(attrs)))
572 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<P<AssocItem>>, Vec<Attribute>)> {
573 self.expect(&token::OpenDelim(token::Brace))?;
574 let attrs = self.parse_inner_attributes()?;
576 let mut impl_items = Vec::new();
577 while !self.eat(&token::CloseDelim(token::Brace)) {
578 let mut at_end = false;
579 match self.parse_impl_item(&mut at_end) {
580 Ok(impl_item) => impl_items.push(impl_item),
584 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
590 Ok((impl_items, attrs))
593 /// Parses defaultness (i.e., `default` or nothing).
594 fn parse_defaultness(&mut self) -> Defaultness {
595 // `pub` is included for better error messages
596 if self.check_keyword(kw::Default)
597 && self.is_keyword_ahead(
611 self.bump(); // `default`
618 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
619 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafe) -> PResult<'a, ItemInfo> {
620 // Parse optional `auto` prefix.
621 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
623 self.expect_keyword(kw::Trait)?;
624 let ident = self.parse_ident()?;
625 let mut tps = self.parse_generics()?;
627 // Parse optional colon and supertrait bounds.
628 let had_colon = self.eat(&token::Colon);
629 let span_at_colon = self.prev_span;
631 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
633 let span_before_eq = self.prev_span;
634 if self.eat(&token::Eq) {
635 // It's a trait alias.
637 let span = span_at_colon.to(span_before_eq);
638 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
641 let bounds = self.parse_generic_bounds(None)?;
642 tps.where_clause = self.parse_where_clause()?;
645 let whole_span = lo.to(self.prev_span);
646 if let IsAuto::Yes = is_auto {
647 let msg = "trait aliases cannot be `auto`";
648 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
650 if let Unsafe::Yes(_) = unsafety {
651 let msg = "trait aliases cannot be `unsafe`";
652 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
655 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
657 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
659 // It's a normal trait.
660 tps.where_clause = self.parse_where_clause()?;
661 self.expect(&token::OpenDelim(token::Brace))?;
662 let mut trait_items = vec![];
663 while !self.eat(&token::CloseDelim(token::Brace)) {
664 if let token::DocComment(_) = self.token.kind {
665 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
670 "found a documentation comment that doesn't document anything",
673 "doc comments must come before what they document, maybe a \
674 comment was intended with `//`?",
681 let mut at_end = false;
682 match self.parse_trait_item(&mut at_end) {
683 Ok(item) => trait_items.push(item),
687 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
693 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
697 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
698 maybe_whole!(self, NtImplItem, |x| x);
699 self.parse_assoc_item(at_end, |_| true)
702 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
703 maybe_whole!(self, NtTraitItem, |x| x);
704 // This is somewhat dubious; We don't want to allow
705 // param names to be left off if there is a definition...
707 // We don't allow param names to be left off in edition 2018.
708 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
711 /// Parses associated items.
715 is_name_required: fn(&token::Token) -> bool,
716 ) -> PResult<'a, P<AssocItem>> {
717 let attrs = self.parse_outer_attributes()?;
718 let mut unclosed_delims = vec![];
719 let (mut item, tokens) = self.collect_tokens(|this| {
720 let item = this.parse_assoc_item_(at_end, attrs, is_name_required);
721 unclosed_delims.append(&mut this.unclosed_delims);
724 self.unclosed_delims.append(&mut unclosed_delims);
725 // See `parse_item` for why this clause is here.
726 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
727 item.tokens = Some(tokens);
732 fn parse_assoc_item_(
735 mut attrs: Vec<Attribute>,
736 is_name_required: fn(&token::Token) -> bool,
737 ) -> PResult<'a, AssocItem> {
738 let lo = self.token.span;
739 let vis = self.parse_visibility(FollowedByType::No)?;
740 let defaultness = self.parse_defaultness();
741 let (name, kind, generics) = if self.eat_keyword(kw::Type) {
742 self.parse_assoc_ty()?
743 } else if self.is_fn_front_matter() {
744 self.parse_assoc_fn(at_end, &mut attrs, is_name_required)?
745 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
746 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
748 self.parse_assoc_const()?
753 span: lo.to(self.prev_span),
764 /// This parses the grammar:
766 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
767 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
768 self.expect_keyword(kw::Const)?;
769 let ident = self.parse_ident()?;
770 self.expect(&token::Colon)?;
771 let ty = self.parse_ty()?;
772 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
774 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
777 /// Parses the following grammar:
779 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
780 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
781 let ident = self.parse_ident()?;
782 let mut generics = self.parse_generics()?;
784 // Parse optional colon and param bounds.
786 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
787 generics.where_clause = self.parse_where_clause()?;
789 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
792 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
795 /// Parses a `UseTree`.
798 /// USE_TREE = [`::`] `*` |
799 /// [`::`] `{` USE_TREE_LIST `}` |
801 /// PATH `::` `{` USE_TREE_LIST `}` |
802 /// PATH [`as` IDENT]
804 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
805 let lo = self.token.span;
807 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
808 let kind = if self.check(&token::OpenDelim(token::Brace))
809 || self.check(&token::BinOp(token::Star))
810 || self.is_import_coupler()
812 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
813 let mod_sep_ctxt = self.token.span.ctxt();
814 if self.eat(&token::ModSep) {
817 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
820 self.parse_use_tree_glob_or_nested()?
822 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
823 prefix = self.parse_path(PathStyle::Mod)?;
825 if self.eat(&token::ModSep) {
826 self.parse_use_tree_glob_or_nested()?
828 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
832 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
835 /// Parses `*` or `{...}`.
836 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
837 Ok(if self.eat(&token::BinOp(token::Star)) {
840 UseTreeKind::Nested(self.parse_use_tree_list()?)
844 /// Parses a `UseTreeKind::Nested(list)`.
847 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
849 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
850 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
854 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
855 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
858 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
859 match self.token.kind {
860 token::Ident(name, false) if name == kw::Underscore => {
861 let span = self.token.span;
863 Ok(Ident::new(name, span))
865 _ => self.parse_ident(),
869 /// Parses `extern crate` links.
874 /// extern crate foo;
875 /// extern crate bar as foo;
877 fn parse_item_extern_crate(
880 visibility: Visibility,
881 attrs: Vec<Attribute>,
882 ) -> PResult<'a, P<Item>> {
883 // Accept `extern crate name-like-this` for better diagnostics
884 let orig_name = self.parse_crate_name_with_dashes()?;
885 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
886 (rename, Some(orig_name.name))
892 let span = lo.to(self.prev_span);
893 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
896 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
897 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
898 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
900 let mut ident = if self.token.is_keyword(kw::SelfLower) {
901 self.parse_path_segment_ident()
905 let mut idents = vec![];
906 let mut replacement = vec![];
907 let mut fixed_crate_name = false;
908 // Accept `extern crate name-like-this` for better diagnostics.
909 let dash = token::BinOp(token::BinOpToken::Minus);
910 if self.token == dash {
911 // Do not include `-` as part of the expected tokens list.
912 while self.eat(&dash) {
913 fixed_crate_name = true;
914 replacement.push((self.prev_span, "_".to_string()));
915 idents.push(self.parse_ident()?);
918 if fixed_crate_name {
919 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
920 let mut fixed_name = format!("{}", ident.name);
922 fixed_name.push_str(&format!("_{}", part.name));
924 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
926 self.struct_span_err(fixed_name_sp, error_msg)
927 .span_label(fixed_name_sp, "dash-separated idents are not valid")
928 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
934 /// Parses `extern` for foreign ABIs modules.
936 /// `extern` is expected to have been
937 /// consumed before calling this method.
941 /// ```ignore (only-for-syntax-highlight)
945 fn parse_item_foreign_mod(
949 visibility: Visibility,
950 mut attrs: Vec<Attribute>,
951 ) -> PResult<'a, P<Item>> {
952 self.expect(&token::OpenDelim(token::Brace))?;
954 attrs.extend(self.parse_inner_attributes()?);
956 let mut foreign_items = vec![];
957 while !self.eat(&token::CloseDelim(token::Brace)) {
958 foreign_items.push(self.parse_foreign_item()?);
961 let prev_span = self.prev_span;
962 let m = ast::ForeignMod { abi, items: foreign_items };
963 let invalid = Ident::invalid();
964 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
967 /// Parses a foreign item.
968 pub fn parse_foreign_item(&mut self) -> PResult<'a, P<ForeignItem>> {
969 maybe_whole!(self, NtForeignItem, |ni| ni);
971 let attrs = self.parse_outer_attributes()?;
972 let lo = self.token.span;
973 let vis = self.parse_visibility(FollowedByType::No)?;
975 if self.check_keyword(kw::Type) {
977 self.parse_item_foreign_type(vis, lo, attrs)
978 } else if self.is_fn_front_matter() {
979 // FOREIGN FUNCTION ITEM
980 self.parse_item_foreign_fn(vis, lo, attrs)
981 } else if self.is_static_global() {
982 // FOREIGN STATIC ITEM
983 self.bump(); // `static`
984 self.parse_item_foreign_static(vis, lo, attrs)
985 } else if self.token.is_keyword(kw::Const) {
986 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
987 self.bump(); // `const`
988 self.struct_span_err(self.prev_span, "extern items cannot be `const`")
991 "try using a static value",
993 Applicability::MachineApplicable,
996 self.parse_item_foreign_static(vis, lo, attrs)
997 } else if let Some(mac) = self.parse_assoc_macro_invoc("extern", Some(&vis), &mut false)? {
998 let kind = ForeignItemKind::Macro(mac);
999 let span = lo.to(self.prev_span);
1000 let ident = Ident::invalid();
1001 Ok(P(ForeignItem { ident, span, id: DUMMY_NODE_ID, attrs, vis, kind, tokens: None }))
1003 if !attrs.is_empty() {
1004 self.expected_item_err(&attrs)?;
1010 /// Parses a static item from a foreign module.
1011 /// Assumes that the `static` keyword is already parsed.
1012 fn parse_item_foreign_static(
1014 vis: ast::Visibility,
1016 attrs: Vec<Attribute>,
1017 ) -> PResult<'a, P<ForeignItem>> {
1018 let mutbl = self.parse_mutability();
1019 let ident = self.parse_ident()?;
1020 self.expect(&token::Colon)?;
1021 let ty = self.parse_ty()?;
1022 let hi = self.token.span;
1023 self.expect_semi()?;
1027 kind: ForeignItemKind::Static(ty, mutbl),
1035 /// Parses a type from a foreign module.
1036 fn parse_item_foreign_type(
1038 vis: ast::Visibility,
1040 attrs: Vec<Attribute>,
1041 ) -> PResult<'a, P<ForeignItem>> {
1042 self.expect_keyword(kw::Type)?;
1044 let ident = self.parse_ident()?;
1045 let hi = self.token.span;
1046 self.expect_semi()?;
1047 Ok(P(ast::ForeignItem {
1050 kind: ForeignItemKind::Ty,
1058 fn is_static_global(&mut self) -> bool {
1059 if self.check_keyword(kw::Static) {
1060 // Check if this could be a closure.
1061 !self.look_ahead(1, |token| {
1062 if token.is_keyword(kw::Move) {
1066 token::BinOp(token::Or) | token::OrOr => true,
1075 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1076 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1078 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1079 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1080 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1082 // Parse the type of a `const` or `static mut?` item.
1083 // That is, the `":" $ty` fragment.
1084 let ty = if self.token == token::Eq {
1085 self.recover_missing_const_type(id, m)
1087 // Not `=` so expect `":"" $ty` as usual.
1088 self.expect(&token::Colon)?;
1092 self.expect(&token::Eq)?;
1093 let e = self.parse_expr()?;
1094 self.expect_semi()?;
1095 let item = match m {
1096 Some(m) => ItemKind::Static(ty, m, e),
1097 None => ItemKind::Const(ty, e),
1099 Ok((id, item, None))
1102 /// We were supposed to parse `:` but instead, we're already at `=`.
1103 /// This means that the type is missing.
1104 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1105 // Construct the error and stash it away with the hope
1106 // that typeck will later enrich the error with a type.
1107 let kind = match m {
1108 Some(Mutability::Mut) => "static mut",
1109 Some(Mutability::Not) => "static",
1112 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1113 err.span_suggestion(
1115 "provide a type for the item",
1116 format!("{}: <type>", id),
1117 Applicability::HasPlaceholders,
1119 err.stash(id.span, StashKey::ItemNoType);
1121 // The user intended that the type be inferred,
1122 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1123 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1126 /// Parses the grammar:
1127 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1128 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1129 let ident = self.parse_ident()?;
1130 let mut tps = self.parse_generics()?;
1131 tps.where_clause = self.parse_where_clause()?;
1132 self.expect(&token::Eq)?;
1133 let ty = self.parse_ty()?;
1134 self.expect_semi()?;
1135 Ok((ident, ty, tps))
1138 /// Parses an enum declaration.
1139 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1140 let id = self.parse_ident()?;
1141 let mut generics = self.parse_generics()?;
1142 generics.where_clause = self.parse_where_clause()?;
1145 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1146 self.recover_stmt();
1150 let enum_definition =
1151 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1152 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1155 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1156 let variant_attrs = self.parse_outer_attributes()?;
1157 let vlo = self.token.span;
1159 let vis = self.parse_visibility(FollowedByType::No)?;
1160 if !self.recover_nested_adt_item(kw::Enum)? {
1163 let ident = self.parse_ident()?;
1165 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1166 // Parse a struct variant.
1167 let (fields, recovered) = self.parse_record_struct_body()?;
1168 VariantData::Struct(fields, recovered)
1169 } else if self.check(&token::OpenDelim(token::Paren)) {
1170 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1172 VariantData::Unit(DUMMY_NODE_ID)
1176 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1178 let vr = ast::Variant {
1182 attrs: variant_attrs,
1185 span: vlo.to(self.prev_span),
1186 is_placeholder: false,
1192 /// Parses `struct Foo { ... }`.
1193 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1194 let class_name = self.parse_ident()?;
1196 let mut generics = self.parse_generics()?;
1198 // There is a special case worth noting here, as reported in issue #17904.
1199 // If we are parsing a tuple struct it is the case that the where clause
1200 // should follow the field list. Like so:
1202 // struct Foo<T>(T) where T: Copy;
1204 // If we are parsing a normal record-style struct it is the case
1205 // that the where clause comes before the body, and after the generics.
1206 // So if we look ahead and see a brace or a where-clause we begin
1207 // parsing a record style struct.
1209 // Otherwise if we look ahead and see a paren we parse a tuple-style
1212 let vdata = if self.token.is_keyword(kw::Where) {
1213 generics.where_clause = self.parse_where_clause()?;
1214 if self.eat(&token::Semi) {
1215 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1216 VariantData::Unit(DUMMY_NODE_ID)
1218 // If we see: `struct Foo<T> where T: Copy { ... }`
1219 let (fields, recovered) = self.parse_record_struct_body()?;
1220 VariantData::Struct(fields, recovered)
1222 // No `where` so: `struct Foo<T>;`
1223 } else if self.eat(&token::Semi) {
1224 VariantData::Unit(DUMMY_NODE_ID)
1225 // Record-style struct definition
1226 } else if self.token == token::OpenDelim(token::Brace) {
1227 let (fields, recovered) = self.parse_record_struct_body()?;
1228 VariantData::Struct(fields, recovered)
1229 // Tuple-style struct definition with optional where-clause.
1230 } else if self.token == token::OpenDelim(token::Paren) {
1231 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1232 generics.where_clause = self.parse_where_clause()?;
1233 self.expect_semi()?;
1236 let token_str = super::token_descr(&self.token);
1238 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1241 let mut err = self.struct_span_err(self.token.span, msg);
1242 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1246 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1249 /// Parses `union Foo { ... }`.
1250 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1251 let class_name = self.parse_ident()?;
1253 let mut generics = self.parse_generics()?;
1255 let vdata = if self.token.is_keyword(kw::Where) {
1256 generics.where_clause = self.parse_where_clause()?;
1257 let (fields, recovered) = self.parse_record_struct_body()?;
1258 VariantData::Struct(fields, recovered)
1259 } else if self.token == token::OpenDelim(token::Brace) {
1260 let (fields, recovered) = self.parse_record_struct_body()?;
1261 VariantData::Struct(fields, recovered)
1263 let token_str = super::token_descr(&self.token);
1264 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1265 let mut err = self.struct_span_err(self.token.span, msg);
1266 err.span_label(self.token.span, "expected `where` or `{` after union name");
1270 Ok((class_name, ItemKind::Union(vdata, generics), None))
1273 pub(super) fn is_union_item(&self) -> bool {
1274 self.token.is_keyword(kw::Union)
1275 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1278 fn parse_record_struct_body(
1280 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1281 let mut fields = Vec::new();
1282 let mut recovered = false;
1283 if self.eat(&token::OpenDelim(token::Brace)) {
1284 while self.token != token::CloseDelim(token::Brace) {
1285 let field = self.parse_struct_decl_field().map_err(|e| {
1286 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1291 Ok(field) => fields.push(field),
1298 self.eat(&token::CloseDelim(token::Brace));
1300 let token_str = super::token_descr(&self.token);
1301 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1302 let mut err = self.struct_span_err(self.token.span, msg);
1303 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1307 Ok((fields, recovered))
1310 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1311 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1312 // Unit like structs are handled in parse_item_struct function
1313 self.parse_paren_comma_seq(|p| {
1314 let attrs = p.parse_outer_attributes()?;
1315 let lo = p.token.span;
1316 let vis = p.parse_visibility(FollowedByType::Yes)?;
1317 let ty = p.parse_ty()?;
1319 span: lo.to(ty.span),
1325 is_placeholder: false,
1331 /// Parses an element of a struct declaration.
1332 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1333 let attrs = self.parse_outer_attributes()?;
1334 let lo = self.token.span;
1335 let vis = self.parse_visibility(FollowedByType::No)?;
1336 self.parse_single_struct_field(lo, vis, attrs)
1339 /// Parses a structure field declaration.
1340 fn parse_single_struct_field(
1344 attrs: Vec<Attribute>,
1345 ) -> PResult<'a, StructField> {
1346 let mut seen_comma: bool = false;
1347 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1348 if self.token == token::Comma {
1351 match self.token.kind {
1355 token::CloseDelim(token::Brace) => {}
1356 token::DocComment(_) => {
1357 let previous_span = self.prev_span;
1358 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1359 self.bump(); // consume the doc comment
1360 let comma_after_doc_seen = self.eat(&token::Comma);
1361 // `seen_comma` is always false, because we are inside doc block
1362 // condition is here to make code more readable
1363 if seen_comma == false && comma_after_doc_seen == true {
1366 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1369 if seen_comma == false {
1370 let sp = self.sess.source_map().next_point(previous_span);
1371 err.span_suggestion(
1373 "missing comma here",
1375 Applicability::MachineApplicable,
1382 let sp = self.prev_span.shrink_to_hi();
1383 let mut err = self.struct_span_err(
1385 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1387 if self.token.is_ident() {
1388 // This is likely another field; emit the diagnostic and keep going
1389 err.span_suggestion(
1391 "try adding a comma",
1393 Applicability::MachineApplicable,
1404 /// Parses a structure field.
1405 fn parse_name_and_ty(
1409 attrs: Vec<Attribute>,
1410 ) -> PResult<'a, StructField> {
1411 let name = self.parse_ident()?;
1412 self.expect(&token::Colon)?;
1413 let ty = self.parse_ty()?;
1415 span: lo.to(self.prev_span),
1421 is_placeholder: false,
1425 pub(super) fn eat_macro_def(
1427 attrs: &[Attribute],
1430 ) -> PResult<'a, Option<P<Item>>> {
1431 let (ident, def) = if self.eat_keyword(kw::Macro) {
1432 let ident = self.parse_ident()?;
1433 let body = if self.check(&token::OpenDelim(token::Brace)) {
1434 self.parse_mac_args()?
1435 } else if self.check(&token::OpenDelim(token::Paren)) {
1436 let params = self.parse_token_tree();
1437 let pspan = params.span();
1438 let body = if self.check(&token::OpenDelim(token::Brace)) {
1439 self.parse_token_tree()
1441 return self.unexpected();
1443 let bspan = body.span();
1444 let tokens = TokenStream::new(vec![
1446 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1449 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1450 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1452 return self.unexpected();
1455 (ident, ast::MacroDef { body, legacy: false })
1456 } else if self.check_keyword(sym::macro_rules)
1457 && self.look_ahead(1, |t| *t == token::Not)
1458 && self.look_ahead(2, |t| t.is_ident())
1460 let prev_span = self.prev_span;
1461 self.complain_if_pub_macro(&vis.node, prev_span);
1465 let ident = self.parse_ident()?;
1466 let body = self.parse_mac_args()?;
1467 if body.need_semicolon() && !self.eat(&token::Semi) {
1468 self.report_invalid_macro_expansion_item();
1471 (ident, ast::MacroDef { body, legacy: true })
1476 let span = lo.to(self.prev_span);
1479 self.sess.gated_spans.gate(sym::decl_macro, span);
1482 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1485 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1487 VisibilityKind::Inherited => {}
1489 let mut err = if self.token.is_keyword(sym::macro_rules) {
1491 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1492 err.span_suggestion(
1494 "try exporting the macro",
1495 "#[macro_export]".to_owned(),
1496 Applicability::MaybeIncorrect, // speculative
1501 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1502 err.help("try adjusting the macro to put `pub` inside the invocation");
1510 fn report_invalid_macro_expansion_item(&self) {
1511 let has_close_delim = self
1514 .span_to_snippet(self.prev_span)
1515 .map(|s| s.ends_with(")") || s.ends_with("]"))
1518 let mut err = self.struct_span_err(
1520 "macros that expand to items must be delimited with braces or followed by a semicolon",
1523 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1524 if has_close_delim {
1525 err.multipart_suggestion(
1526 "change the delimiters to curly braces",
1528 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1529 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1531 Applicability::MaybeIncorrect,
1534 err.span_suggestion(
1536 "change the delimiters to curly braces",
1537 " { /* items */ }".to_string(),
1538 Applicability::HasPlaceholders,
1542 err.span_suggestion(
1543 self.prev_span.shrink_to_hi(),
1546 Applicability::MaybeIncorrect,
1551 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1552 /// it is, we try to parse the item and report error about nested types.
1553 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1554 if (self.token.is_keyword(kw::Enum)
1555 || self.token.is_keyword(kw::Struct)
1556 || self.token.is_keyword(kw::Union))
1557 && self.look_ahead(1, |t| t.is_ident())
1559 let kw_token = self.token.clone();
1560 let kw_str = pprust::token_to_string(&kw_token);
1561 let item = self.parse_item()?;
1563 self.struct_span_err(
1565 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1569 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1571 Applicability::MaybeIncorrect,
1574 // We successfully parsed the item but we must inform the caller about nested problem.
1586 attrs: Vec<Attribute>,
1588 P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None })
1592 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1593 pub(super) struct ParamCfg {
1594 /// `is_name_required` decides if, per-parameter,
1595 /// the parameter must have a pattern or just a type.
1596 pub is_name_required: fn(&token::Token) -> bool,
1600 /// Configuration for a free function in the sense that it is not associated.
1601 const FREE: Self = ParamCfg { is_name_required: |_| true };
1604 /// Parsing of functions and methods.
1605 impl<'a> Parser<'a> {
1606 /// Parses an item-position function declaration.
1611 mut attrs: Vec<Attribute>,
1612 ) -> PResult<'a, Option<P<Item>>> {
1613 let (ident, sig, generics, body) =
1614 self.parse_fn(&mut false, &mut attrs, &ParamCfg::FREE)?;
1615 let kind = ItemKind::Fn(sig, generics, body);
1616 self.mk_item_with_info(attrs, lo, vis, (ident, kind, None))
1619 /// Parses a function declaration from a foreign module.
1620 fn parse_item_foreign_fn(
1622 vis: ast::Visibility,
1624 mut attrs: Vec<Attribute>,
1625 ) -> PResult<'a, P<ForeignItem>> {
1626 let (ident, sig, generics, body) =
1627 self.parse_fn(&mut false, &mut attrs, &ParamCfg::FREE)?;
1628 let kind = ForeignItemKind::Fn(sig, generics, body);
1629 let span = lo.to(self.prev_span);
1630 Ok(P(ast::ForeignItem { ident, attrs, kind, id: DUMMY_NODE_ID, span, vis, tokens: None }))
1636 attrs: &mut Vec<Attribute>,
1637 is_name_required: fn(&token::Token) -> bool,
1638 ) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
1639 let cfg = ParamCfg { is_name_required };
1640 let (ident, sig, generics, body) = self.parse_fn(at_end, attrs, &cfg)?;
1641 Ok((ident, AssocItemKind::Fn(sig, body), generics))
1644 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1648 attrs: &mut Vec<Attribute>,
1650 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1651 let header = self.parse_fn_front_matter()?; // `const ... fn`
1652 let ident = self.parse_ident()?; // `foo`
1653 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1654 let decl = self.parse_fn_decl(cfg, AllowPlus::Yes)?; // `(p: u8, ...)`
1655 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1656 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1657 Ok((ident, FnSig { header, decl }, generics, body))
1660 /// Parse the "body" of a function.
1661 /// This can either be `;` when there's no body,
1662 /// or e.g. a block when the function is a provided one.
1666 attrs: &mut Vec<Attribute>,
1667 ) -> PResult<'a, Option<P<Block>>> {
1668 let (inner_attrs, body) = match self.token.kind {
1673 token::OpenDelim(token::Brace) => {
1674 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1677 token::Interpolated(ref nt) => match **nt {
1678 token::NtBlock(..) => {
1679 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1682 _ => return self.expected_semi_or_open_brace(),
1684 _ => return self.expected_semi_or_open_brace(),
1686 attrs.extend(inner_attrs);
1691 /// Is the current token the start of an `FnHeader` / not a valid parse?
1692 fn is_fn_front_matter(&mut self) -> bool {
1693 // We use an over-approximation here.
1694 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1695 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1696 self.check_keyword(kw::Fn) // Definitely an `fn`.
1697 // `$qual fn` or `$qual $qual`:
1698 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1699 && self.look_ahead(1, |t| {
1700 // ...qualified and then `fn`, e.g. `const fn`.
1701 t.is_keyword(kw::Fn)
1702 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1703 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1706 || self.check_keyword(kw::Extern)
1707 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1708 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1711 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1712 /// up to and including the `fn` keyword. The formal grammar is:
1715 /// Extern = "extern" StringLit ;
1716 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1717 /// FnFrontMatter = FnQual? "fn" ;
1719 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1720 let constness = self.parse_constness();
1721 let asyncness = self.parse_asyncness();
1722 let unsafety = self.parse_unsafety();
1723 let ext = self.parse_extern()?;
1725 if let Async::Yes { span, .. } = asyncness {
1726 self.ban_async_in_2015(span);
1729 if !self.eat_keyword(kw::Fn) {
1730 // It is possible for `expect_one_of` to recover given the contents of
1731 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1732 // account for this.
1733 if !self.expect_one_of(&[], &[])? {
1738 Ok(FnHeader { constness, unsafety, asyncness, ext })
1741 /// Parses the parameter list and result type of a function declaration.
1742 pub(super) fn parse_fn_decl(
1745 ret_allow_plus: AllowPlus,
1746 ) -> PResult<'a, P<FnDecl>> {
1748 inputs: self.parse_fn_params(cfg)?,
1749 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1753 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1754 fn parse_fn_params(&mut self, cfg: &ParamCfg) -> PResult<'a, Vec<Param>> {
1755 let mut first_param = true;
1756 // Parse the arguments, starting out with `self` being allowed...
1757 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1758 let param = p.parse_param_general(&cfg, first_param).or_else(|mut e| {
1760 let lo = p.prev_span;
1761 // Skip every token until next possible arg or end.
1762 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1763 // Create a placeholder argument for proper arg count (issue #34264).
1764 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1766 // ...now that we've parsed the first argument, `self` is no longer allowed.
1767 first_param = false;
1770 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1771 self.deduplicate_recovered_params_names(&mut params);
1775 /// Parses a single function parameter.
1777 /// - `self` is syntactically allowed when `first_param` holds.
1778 fn parse_param_general(&mut self, cfg: &ParamCfg, first_param: bool) -> PResult<'a, Param> {
1779 let lo = self.token.span;
1780 let attrs = self.parse_outer_attributes()?;
1782 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1783 if let Some(mut param) = self.parse_self_param()? {
1784 param.attrs = attrs.into();
1785 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1788 let is_name_required = match self.token.kind {
1789 token::DotDotDot => false,
1790 _ => (cfg.is_name_required)(&self.token),
1792 let (pat, ty) = if is_name_required || self.is_named_param() {
1793 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1795 let pat = self.parse_fn_param_pat()?;
1796 if let Err(mut err) = self.expect(&token::Colon) {
1797 return if let Some(ident) =
1798 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1801 Ok(dummy_arg(ident))
1807 self.eat_incorrect_doc_comment_for_param_type();
1808 (pat, self.parse_ty_for_param()?)
1810 debug!("parse_param_general ident_to_pat");
1811 let parser_snapshot_before_ty = self.clone();
1812 self.eat_incorrect_doc_comment_for_param_type();
1813 let mut ty = self.parse_ty_for_param();
1815 && self.token != token::Comma
1816 && self.token != token::CloseDelim(token::Paren)
1818 // This wasn't actually a type, but a pattern looking like a type,
1819 // so we are going to rollback and re-parse for recovery.
1820 ty = self.unexpected();
1824 let ident = Ident::new(kw::Invalid, self.prev_span);
1825 let bm = BindingMode::ByValue(Mutability::Not);
1826 let pat = self.mk_pat_ident(ty.span, bm, ident);
1829 // If this is a C-variadic argument and we hit an error, return the error.
1830 Err(err) if self.token == token::DotDotDot => return Err(err),
1831 // Recover from attempting to parse the argument as a type without pattern.
1834 mem::replace(self, parser_snapshot_before_ty);
1835 self.recover_arg_parse()?
1840 let span = lo.to(self.token.span);
1843 attrs: attrs.into(),
1844 id: ast::DUMMY_NODE_ID,
1845 is_placeholder: false,
1852 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1853 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1854 // Extract an identifier *after* having confirmed that the token is one.
1855 let expect_self_ident = |this: &mut Self| {
1856 match this.token.kind {
1857 // Preserve hygienic context.
1858 token::Ident(name, _) => {
1859 let span = this.token.span;
1861 Ident::new(name, span)
1863 _ => unreachable!(),
1866 // Is `self` `n` tokens ahead?
1867 let is_isolated_self = |this: &Self, n| {
1868 this.is_keyword_ahead(n, &[kw::SelfLower])
1869 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1871 // Is `mut self` `n` tokens ahead?
1872 let is_isolated_mut_self =
1873 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1874 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1875 let parse_self_possibly_typed = |this: &mut Self, m| {
1876 let eself_ident = expect_self_ident(this);
1877 let eself_hi = this.prev_span;
1878 let eself = if this.eat(&token::Colon) {
1879 SelfKind::Explicit(this.parse_ty()?, m)
1883 Ok((eself, eself_ident, eself_hi))
1885 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1886 let recover_self_ptr = |this: &mut Self| {
1887 let msg = "cannot pass `self` by raw pointer";
1888 let span = this.token.span;
1889 this.struct_span_err(span, msg).span_label(span, msg).emit();
1891 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1894 // Parse optional `self` parameter of a method.
1895 // Only a limited set of initial token sequences is considered `self` parameters; anything
1896 // else is parsed as a normal function parameter list, so some lookahead is required.
1897 let eself_lo = self.token.span;
1898 let (eself, eself_ident, eself_hi) = match self.token.kind {
1899 token::BinOp(token::And) => {
1900 let eself = if is_isolated_self(self, 1) {
1903 SelfKind::Region(None, Mutability::Not)
1904 } else if is_isolated_mut_self(self, 1) {
1908 SelfKind::Region(None, Mutability::Mut)
1909 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1912 let lt = self.expect_lifetime();
1913 SelfKind::Region(Some(lt), Mutability::Not)
1914 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1917 let lt = self.expect_lifetime();
1919 SelfKind::Region(Some(lt), Mutability::Mut)
1924 (eself, expect_self_ident(self), self.prev_span)
1927 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1929 recover_self_ptr(self)?
1931 // `*mut self` and `*const self`
1932 token::BinOp(token::Star)
1933 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1937 recover_self_ptr(self)?
1939 // `self` and `self: TYPE`
1940 token::Ident(..) if is_isolated_self(self, 0) => {
1941 parse_self_possibly_typed(self, Mutability::Not)?
1943 // `mut self` and `mut self: TYPE`
1944 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1946 parse_self_possibly_typed(self, Mutability::Mut)?
1948 _ => return Ok(None),
1951 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1952 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1955 fn is_named_param(&self) -> bool {
1956 let offset = match self.token.kind {
1957 token::Interpolated(ref nt) => match **nt {
1958 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1961 token::BinOp(token::And) | token::AndAnd => 1,
1962 _ if self.token.is_keyword(kw::Mut) => 1,
1966 self.look_ahead(offset, |t| t.is_ident())
1967 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1970 fn recover_first_param(&mut self) -> &'static str {
1972 .parse_outer_attributes()
1973 .and_then(|_| self.parse_self_param())
1974 .map_err(|mut e| e.cancel())
1976 Ok(Some(_)) => "method",