1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
3 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
7 use rustc_ast::token::{self, TokenKind};
8 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
9 use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
10 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
11 use rustc_ast::{BindingMode, Block, FnDecl, FnSig, Param, SelfKind};
12 use rustc_ast::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData};
13 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
14 use rustc_ast::{MacArgs, MacCall, MacDelimiter};
15 use rustc_ast_pretty::pprust;
16 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
17 use rustc_span::edition::{Edition, LATEST_STABLE_EDITION};
18 use rustc_span::source_map::{self, Span};
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use std::convert::TryFrom;
26 /// Parses a source module as a crate. This is the main entry point for the parser.
27 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
28 let (attrs, items, span) = self.parse_mod(&token::Eof)?;
29 let proc_macros = Vec::new(); // Filled in by `proc_macro_harness::inject()`.
30 Ok(ast::Crate { attrs, items, span, proc_macros })
33 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
34 fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
35 let unsafety = self.parse_unsafety();
36 self.expect_keyword(kw::Mod)?;
37 let id = self.parse_ident()?;
38 let mod_kind = if self.eat(&token::Semi) {
41 self.expect(&token::OpenDelim(token::Brace))?;
42 let (mut inner_attrs, items, inner_span) =
43 self.parse_mod(&token::CloseDelim(token::Brace))?;
44 attrs.append(&mut inner_attrs);
45 ModKind::Loaded(items, Inline::Yes, inner_span)
47 Ok((id, ItemKind::Mod(unsafety, mod_kind)))
50 /// Parses the contents of a module (inner attributes followed by module items).
54 ) -> PResult<'a, (Vec<Attribute>, Vec<P<Item>>, Span)> {
55 let lo = self.token.span;
56 let attrs = self.parse_inner_attributes()?;
58 let mut items = vec![];
59 while let Some(item) = self.parse_item(ForceCollect::No)? {
61 self.maybe_consume_incorrect_semicolon(&items);
65 let token_str = super::token_descr(&self.token);
66 if !self.maybe_consume_incorrect_semicolon(&items) {
67 let msg = &format!("expected item, found {}", token_str);
68 let mut err = self.struct_span_err(self.token.span, msg);
69 err.span_label(self.token.span, "expected item");
74 Ok((attrs, items, lo.to(self.prev_token.span)))
78 pub(super) type ItemInfo = (Ident, ItemKind);
81 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
82 self.parse_item_(|_| true, force_collect).map(|i| i.map(P))
88 force_collect: ForceCollect,
89 ) -> PResult<'a, Option<Item>> {
90 let attrs = self.parse_outer_attributes()?;
91 self.parse_item_common(attrs, true, false, req_name, force_collect)
94 pub(super) fn parse_item_common(
100 force_collect: ForceCollect,
101 ) -> PResult<'a, Option<Item>> {
102 // Don't use `maybe_whole` so that we have precise control
103 // over when we bump the parser
104 if let token::Interpolated(nt) = &self.token.kind {
105 if let token::NtItem(item) = &**nt {
106 let mut item = item.clone();
109 attrs.prepend_to_nt_inner(&mut item.attrs);
110 return Ok(Some(item.into_inner()));
114 let mut unclosed_delims = vec![];
116 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
117 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
118 unclosed_delims.append(&mut this.unclosed_delims);
119 Ok((item?, TrailingToken::None))
122 self.unclosed_delims.append(&mut unclosed_delims);
126 fn parse_item_common_(
128 mut attrs: Vec<Attribute>,
132 ) -> PResult<'a, Option<Item>> {
133 let lo = self.token.span;
134 let vis = self.parse_visibility(FollowedByType::No)?;
135 let mut def = self.parse_defaultness();
136 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
137 if let Some((ident, kind)) = kind {
138 self.error_on_unconsumed_default(def, &kind);
139 let span = lo.to(self.prev_token.span);
140 let id = DUMMY_NODE_ID;
141 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
142 return Ok(Some(item));
145 // At this point, we have failed to parse an item.
146 self.error_on_unmatched_vis(&vis);
147 self.error_on_unmatched_defaultness(def);
149 self.recover_attrs_no_item(&attrs)?;
154 /// Error in-case a non-inherited visibility was parsed but no item followed.
155 fn error_on_unmatched_vis(&self, vis: &Visibility) {
156 if let VisibilityKind::Inherited = vis.kind {
159 let vs = pprust::vis_to_string(&vis);
160 let vs = vs.trim_end();
161 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
162 .span_label(vis.span, "the visibility")
163 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
167 /// Error in-case a `default` was parsed but no item followed.
168 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
169 if let Defaultness::Default(sp) = def {
170 self.struct_span_err(sp, "`default` is not followed by an item")
171 .span_label(sp, "the `default` qualifier")
172 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
177 /// Error in-case `default` was parsed in an in-appropriate context.
178 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
179 if let Defaultness::Default(span) = def {
180 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
181 self.struct_span_err(span, &msg)
182 .span_label(span, "`default` because of this")
183 .note("only associated `fn`, `const`, and `type` items can be `default`")
188 /// Parses one of the items allowed by the flags.
191 attrs: &mut Vec<Attribute>,
192 macros_allowed: bool,
195 def: &mut Defaultness,
197 ) -> PResult<'a, Option<ItemInfo>> {
198 let def_final = def == &Defaultness::Final;
199 let mut def = || mem::replace(def, Defaultness::Final);
201 let info = if self.eat_keyword(kw::Use) {
203 let tree = self.parse_use_tree()?;
205 // If wildcard or glob-like brace syntax doesn't have `;`,
206 // the user may not know `*` or `{}` should be the last.
207 if let Err(mut e) = self.expect_semi() {
209 UseTreeKind::Glob => {
210 e.note("the wildcard token must be last on the path").emit();
212 UseTreeKind::Nested(..) => {
213 e.note("glob-like brace syntax must be last on the path").emit();
220 (Ident::invalid(), ItemKind::Use(tree))
221 } else if self.check_fn_front_matter(def_final) {
223 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name, lo)?;
224 (ident, ItemKind::Fn(box FnKind(def(), sig, generics, body)))
225 } else if self.eat_keyword(kw::Extern) {
226 if self.eat_keyword(kw::Crate) {
228 self.parse_item_extern_crate()?
231 self.parse_item_foreign_mod(attrs, Unsafe::No)?
233 } else if self.is_unsafe_foreign_mod() {
235 let unsafety = self.parse_unsafety();
236 self.expect_keyword(kw::Extern)?;
237 self.parse_item_foreign_mod(attrs, unsafety)?
238 } else if self.is_static_global() {
240 self.bump(); // `static`
241 let m = self.parse_mutability();
242 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
243 (ident, ItemKind::Static(ty, m, expr))
244 } else if let Const::Yes(const_span) = self.parse_constness() {
246 if self.token.is_keyword(kw::Impl) {
247 // recover from `const impl`, suggest `impl const`
248 self.recover_const_impl(const_span, attrs, def())?
250 self.recover_const_mut(const_span);
251 let (ident, ty, expr) = self.parse_item_global(None)?;
252 (ident, ItemKind::Const(def(), ty, expr))
254 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
256 self.parse_item_trait(attrs, lo)?
257 } else if self.check_keyword(kw::Impl)
258 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
261 self.parse_item_impl(attrs, def())?
262 } else if self.check_keyword(kw::Mod)
263 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
266 self.parse_item_mod(attrs)?
267 } else if self.eat_keyword(kw::Type) {
269 self.parse_type_alias(def())?
270 } else if self.eat_keyword(kw::Enum) {
272 self.parse_item_enum()?
273 } else if self.eat_keyword(kw::Struct) {
275 self.parse_item_struct()?
276 } else if self.is_kw_followed_by_ident(kw::Union) {
278 self.bump(); // `union`
279 self.parse_item_union()?
280 } else if self.eat_keyword(kw::Macro) {
282 self.parse_item_decl_macro(lo)?
283 } else if self.is_macro_rules_item() {
285 self.parse_item_macro_rules(vis)?
286 } else if vis.kind.is_pub() && self.isnt_macro_invocation() {
287 self.recover_missing_kw_before_item()?;
289 } else if macros_allowed && self.check_path() {
290 // MACRO INVOCATION ITEM
291 (Ident::invalid(), ItemKind::MacCall(self.parse_item_macro(vis)?))
298 /// When parsing a statement, would the start of a path be an item?
299 pub(super) fn is_path_start_item(&mut self) -> bool {
300 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
301 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
302 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
303 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
304 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
307 /// Are we sure this could not possibly be a macro invocation?
308 fn isnt_macro_invocation(&mut self) -> bool {
309 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
312 /// Recover on encountering a struct or method definition where the user
313 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
314 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
315 // Space between `pub` keyword and the identifier
318 // ^^^ `sp` points here
319 let sp = self.prev_token.span.between(self.token.span);
320 let full_sp = self.prev_token.span.to(self.token.span);
321 let ident_sp = self.token.span;
322 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
323 // possible public struct definition where `struct` was forgotten
324 let ident = self.parse_ident().unwrap();
325 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
326 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
327 err.span_suggestion_short(
331 Applicability::MaybeIncorrect, // speculative
334 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
335 let ident = self.parse_ident().unwrap();
337 let kw_name = self.recover_first_param();
338 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
339 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
340 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
342 ("fn", kw_name, false)
343 } else if self.check(&token::OpenDelim(token::Brace)) {
345 ("fn", kw_name, false)
346 } else if self.check(&token::Colon) {
350 ("fn` or `struct", "function or struct", true)
353 let msg = format!("missing `{}` for {} definition", kw, kw_name);
354 let mut err = self.struct_span_err(sp, &msg);
356 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
358 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
359 err.span_suggestion_short(
363 Applicability::MachineApplicable,
365 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
368 "if you meant to call a macro, try",
369 format!("{}!", snippet),
370 // this is the `ambiguous` conditional branch
371 Applicability::MaybeIncorrect,
375 "if you meant to call a macro, remove the `pub` \
376 and add a trailing `!` after the identifier",
380 } else if self.look_ahead(1, |t| *t == token::Lt) {
381 let ident = self.parse_ident().unwrap();
382 self.eat_to_tokens(&[&token::Gt]);
384 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
385 ("fn", self.recover_first_param(), false)
386 } else if self.check(&token::OpenDelim(token::Brace)) {
387 ("struct", "struct", false)
389 ("fn` or `struct", "function or struct", true)
391 let msg = format!("missing `{}` for {} definition", kw, kw_name);
392 let mut err = self.struct_span_err(sp, &msg);
394 err.span_suggestion_short(
396 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
398 Applicability::MachineApplicable,
407 /// Parses an item macro, e.g., `item!();`.
408 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
409 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
410 self.expect(&token::Not)?; // `!`
411 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
412 self.eat_semi_for_macro_if_needed(&args);
413 self.complain_if_pub_macro(vis, false);
414 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
417 /// Recover if we parsed attributes and expected an item but there was none.
418 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
419 let (start, end) = match attrs {
421 [x0 @ xn] | [x0, .., xn] => (x0, xn),
423 let msg = if end.is_doc_comment() {
424 "expected item after doc comment"
426 "expected item after attributes"
428 let mut err = self.struct_span_err(end.span, msg);
429 if end.is_doc_comment() {
430 err.span_label(end.span, "this doc comment doesn't document anything");
432 if let [.., penultimate, _] = attrs {
433 err.span_label(start.span.to(penultimate.span), "other attributes here");
438 fn is_async_fn(&self) -> bool {
439 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
442 fn parse_polarity(&mut self) -> ast::ImplPolarity {
443 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
444 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
446 ast::ImplPolarity::Negative(self.prev_token.span)
448 ast::ImplPolarity::Positive
452 /// Parses an implementation item.
455 /// impl<'a, T> TYPE { /* impl items */ }
456 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
457 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
458 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
461 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
463 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
464 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
468 attrs: &mut Vec<Attribute>,
469 defaultness: Defaultness,
470 ) -> PResult<'a, ItemInfo> {
471 let unsafety = self.parse_unsafety();
472 self.expect_keyword(kw::Impl)?;
474 // First, parse generic parameters if necessary.
475 let mut generics = if self.choose_generics_over_qpath(0) {
476 self.parse_generics()?
478 let mut generics = Generics::default();
480 // /\ this is where `generics.span` should point when there are no type params.
481 generics.span = self.prev_token.span.shrink_to_hi();
485 let constness = self.parse_constness();
486 if let Const::Yes(span) = constness {
487 self.sess.gated_spans.gate(sym::const_trait_impl, span);
490 let polarity = self.parse_polarity();
492 // Parse both types and traits as a type, then reinterpret if necessary.
493 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
494 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
496 let span = self.prev_token.span.between(self.token.span);
497 self.struct_span_err(span, "missing trait in a trait impl").emit();
499 kind: TyKind::Path(None, err_path(span)),
508 // If `for` is missing we try to recover.
509 let has_for = self.eat_keyword(kw::For);
510 let missing_for_span = self.prev_token.span.between(self.token.span);
512 let ty_second = if self.token == token::DotDot {
513 // We need to report this error after `cfg` expansion for compatibility reasons
514 self.bump(); // `..`, do not add it to expected tokens
515 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
516 } else if has_for || self.token.can_begin_type() {
517 Some(self.parse_ty()?)
522 generics.where_clause = self.parse_where_clause()?;
524 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
526 let item_kind = match ty_second {
528 // impl Trait for Type
530 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
531 .span_suggestion_short(
535 Applicability::MachineApplicable,
540 let ty_first = ty_first.into_inner();
541 let path = match ty_first.kind {
542 // This notably includes paths passed through `ty` macro fragments (#46438).
543 TyKind::Path(None, path) => path,
545 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
546 err_path(ty_first.span)
549 let trait_ref = TraitRef { path, ref_id: ty_first.id };
551 ItemKind::Impl(box ImplKind {
557 of_trait: Some(trait_ref),
564 ItemKind::Impl(box ImplKind {
577 Ok((Ident::invalid(), item_kind))
580 fn parse_item_list<T>(
582 attrs: &mut Vec<Attribute>,
583 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
584 ) -> PResult<'a, Vec<T>> {
585 let open_brace_span = self.token.span;
586 self.expect(&token::OpenDelim(token::Brace))?;
587 attrs.append(&mut self.parse_inner_attributes()?);
589 let mut items = Vec::new();
590 while !self.eat(&token::CloseDelim(token::Brace)) {
591 if self.recover_doc_comment_before_brace() {
594 match parse_item(self) {
596 // We have to bail or we'll potentially never make progress.
597 let non_item_span = self.token.span;
598 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
599 self.struct_span_err(non_item_span, "non-item in item list")
600 .span_label(open_brace_span, "item list starts here")
601 .span_label(non_item_span, "non-item starts here")
602 .span_label(self.prev_token.span, "item list ends here")
606 Ok(Some(item)) => items.extend(item),
608 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
609 err.span_label(open_brace_span, "while parsing this item list starting here")
610 .span_label(self.prev_token.span, "the item list ends here")
619 /// Recover on a doc comment before `}`.
620 fn recover_doc_comment_before_brace(&mut self) -> bool {
621 if let token::DocComment(..) = self.token.kind {
622 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
627 "found a documentation comment that doesn't document anything",
629 .span_label(self.token.span, "this doc comment doesn't document anything")
631 "doc comments must come before what they document, maybe a \
632 comment was intended with `//`?",
642 /// Parses defaultness (i.e., `default` or nothing).
643 fn parse_defaultness(&mut self) -> Defaultness {
644 // We are interested in `default` followed by another identifier.
645 // However, we must avoid keywords that occur as binary operators.
646 // Currently, the only applicable keyword is `as` (`default as Ty`).
647 if self.check_keyword(kw::Default)
648 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
650 self.bump(); // `default`
651 Defaultness::Default(self.prev_token.uninterpolated_span())
657 /// Is this an `(unsafe auto? | auto) trait` item?
658 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
660 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
662 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
665 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
666 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
667 let unsafety = self.parse_unsafety();
668 // Parse optional `auto` prefix.
669 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
671 self.expect_keyword(kw::Trait)?;
672 let ident = self.parse_ident()?;
673 let mut tps = self.parse_generics()?;
675 // Parse optional colon and supertrait bounds.
676 let had_colon = self.eat(&token::Colon);
677 let span_at_colon = self.prev_token.span;
678 let bounds = if had_colon {
679 self.parse_generic_bounds(Some(self.prev_token.span))?
684 let span_before_eq = self.prev_token.span;
685 if self.eat(&token::Eq) {
686 // It's a trait alias.
688 let span = span_at_colon.to(span_before_eq);
689 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
692 let bounds = self.parse_generic_bounds(None)?;
693 tps.where_clause = self.parse_where_clause()?;
696 let whole_span = lo.to(self.prev_token.span);
697 if is_auto == IsAuto::Yes {
698 let msg = "trait aliases cannot be `auto`";
699 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
701 if let Unsafe::Yes(_) = unsafety {
702 let msg = "trait aliases cannot be `unsafe`";
703 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
706 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
708 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
710 // It's a normal trait.
711 tps.where_clause = self.parse_where_clause()?;
712 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
713 Ok((ident, ItemKind::Trait(box TraitKind(is_auto, unsafety, tps, bounds, items))))
717 pub fn parse_impl_item(
719 force_collect: ForceCollect,
720 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
721 self.parse_assoc_item(|_| true, force_collect)
724 pub fn parse_trait_item(
726 force_collect: ForceCollect,
727 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
728 self.parse_assoc_item(|edition| edition >= Edition::Edition2018, force_collect)
731 /// Parses associated items.
735 force_collect: ForceCollect,
736 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
737 Ok(self.parse_item_(req_name, force_collect)?.map(
738 |Item { attrs, id, span, vis, ident, kind, tokens }| {
739 let kind = match AssocItemKind::try_from(kind) {
741 Err(kind) => match kind {
742 ItemKind::Static(a, _, b) => {
743 self.struct_span_err(span, "associated `static` items are not allowed")
745 AssocItemKind::Const(Defaultness::Final, a, b)
747 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
750 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
755 /// Parses a `type` alias with the following grammar:
757 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
759 /// The `"type"` has already been eaten.
760 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
761 let ident = self.parse_ident()?;
762 let mut generics = self.parse_generics()?;
764 // Parse optional colon and param bounds.
766 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
767 generics.where_clause = self.parse_where_clause()?;
769 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
772 Ok((ident, ItemKind::TyAlias(box TyAliasKind(def, generics, bounds, default))))
775 /// Parses a `UseTree`.
778 /// USE_TREE = [`::`] `*` |
779 /// [`::`] `{` USE_TREE_LIST `}` |
781 /// PATH `::` `{` USE_TREE_LIST `}` |
782 /// PATH [`as` IDENT]
784 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
785 let lo = self.token.span;
787 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
788 let kind = if self.check(&token::OpenDelim(token::Brace))
789 || self.check(&token::BinOp(token::Star))
790 || self.is_import_coupler()
792 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
793 let mod_sep_ctxt = self.token.span.ctxt();
794 if self.eat(&token::ModSep) {
797 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
800 self.parse_use_tree_glob_or_nested()?
802 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
803 prefix = self.parse_path(PathStyle::Mod)?;
805 if self.eat(&token::ModSep) {
806 self.parse_use_tree_glob_or_nested()?
808 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
812 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
815 /// Parses `*` or `{...}`.
816 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
817 Ok(if self.eat(&token::BinOp(token::Star)) {
820 UseTreeKind::Nested(self.parse_use_tree_list()?)
824 /// Parses a `UseTreeKind::Nested(list)`.
827 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
829 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
830 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
834 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
835 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
838 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
839 match self.token.ident() {
840 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
844 _ => self.parse_ident(),
848 /// Parses `extern crate` links.
853 /// extern crate foo;
854 /// extern crate bar as foo;
856 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
857 // Accept `extern crate name-like-this` for better diagnostics
858 let orig_name = self.parse_crate_name_with_dashes()?;
859 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
860 (rename, Some(orig_name.name))
865 Ok((item_name, ItemKind::ExternCrate(orig_name)))
868 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
869 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
870 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
872 let mut ident = if self.token.is_keyword(kw::SelfLower) {
873 self.parse_path_segment_ident()
877 let mut idents = vec![];
878 let mut replacement = vec![];
879 let mut fixed_crate_name = false;
880 // Accept `extern crate name-like-this` for better diagnostics.
881 let dash = token::BinOp(token::BinOpToken::Minus);
882 if self.token == dash {
883 // Do not include `-` as part of the expected tokens list.
884 while self.eat(&dash) {
885 fixed_crate_name = true;
886 replacement.push((self.prev_token.span, "_".to_string()));
887 idents.push(self.parse_ident()?);
890 if fixed_crate_name {
891 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
892 let mut fixed_name = format!("{}", ident.name);
894 fixed_name.push_str(&format!("_{}", part.name));
896 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
898 self.struct_span_err(fixed_name_sp, error_msg)
899 .span_label(fixed_name_sp, "dash-separated idents are not valid")
900 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
906 /// Parses `extern` for foreign ABIs modules.
908 /// `extern` is expected to have been consumed before calling this method.
912 /// ```ignore (only-for-syntax-highlight)
916 fn parse_item_foreign_mod(
918 attrs: &mut Vec<Attribute>,
920 ) -> PResult<'a, ItemInfo> {
921 let abi = self.parse_abi(); // ABI?
922 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?;
923 let module = ast::ForeignMod { unsafety, abi, items };
924 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
927 /// Parses a foreign item (one in an `extern { ... }` block).
928 pub fn parse_foreign_item(
930 force_collect: ForceCollect,
931 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
932 Ok(self.parse_item_(|_| true, force_collect)?.map(
933 |Item { attrs, id, span, vis, ident, kind, tokens }| {
934 let kind = match ForeignItemKind::try_from(kind) {
936 Err(kind) => match kind {
937 ItemKind::Const(_, a, b) => {
938 self.error_on_foreign_const(span, ident);
939 ForeignItemKind::Static(a, Mutability::Not, b)
941 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
944 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
949 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
950 let span = self.sess.source_map().guess_head_span(span);
951 let descr = kind.descr();
952 self.struct_span_err(span, &format!("{} is not supported in {}", descr, ctx))
953 .help(&format!("consider moving the {} out to a nearby module scope", descr))
958 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
959 self.struct_span_err(ident.span, "extern items cannot be `const`")
961 span.with_hi(ident.span.lo()),
962 "try using a static value",
963 "static ".to_string(),
964 Applicability::MachineApplicable,
966 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
970 fn is_unsafe_foreign_mod(&self) -> bool {
971 self.token.is_keyword(kw::Unsafe)
972 && self.is_keyword_ahead(1, &[kw::Extern])
974 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
975 |t| t.kind == token::OpenDelim(token::Brace),
979 fn is_static_global(&mut self) -> bool {
980 if self.check_keyword(kw::Static) {
981 // Check if this could be a closure.
982 !self.look_ahead(1, |token| {
983 if token.is_keyword(kw::Move) {
986 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
993 /// Recover on `const mut` with `const` already eaten.
994 fn recover_const_mut(&mut self, const_span: Span) {
995 if self.eat_keyword(kw::Mut) {
996 let span = self.prev_token.span;
997 self.struct_span_err(span, "const globals cannot be mutable")
998 .span_label(span, "cannot be mutable")
1001 "you might want to declare a static instead",
1002 "static".to_owned(),
1003 Applicability::MaybeIncorrect,
1009 /// Recover on `const impl` with `const` already eaten.
1010 fn recover_const_impl(
1013 attrs: &mut Vec<Attribute>,
1014 defaultness: Defaultness,
1015 ) -> PResult<'a, ItemInfo> {
1016 let impl_span = self.token.span;
1017 let mut err = self.expected_ident_found();
1019 // Only try to recover if this is implementing a trait for a type
1020 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1021 Ok(impl_info) => impl_info,
1022 Err(mut recovery_error) => {
1023 // Recovery failed, raise the "expected identifier" error
1024 recovery_error.cancel();
1030 ItemKind::Impl(box ImplKind {
1031 of_trait: Some(ref trai), ref mut constness, ..
1033 *constness = Const::Yes(const_span);
1035 let before_trait = trai.path.span.shrink_to_lo();
1036 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1037 err.multipart_suggestion(
1038 "you might have meant to write a const trait impl",
1039 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1040 Applicability::MaybeIncorrect,
1044 ItemKind::Impl { .. } => return Err(err),
1045 _ => unreachable!(),
1051 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1052 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1054 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1055 fn parse_item_global(
1057 m: Option<Mutability>,
1058 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1059 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1061 // Parse the type of a `const` or `static mut?` item.
1062 // That is, the `":" $ty` fragment.
1063 let ty = if self.eat(&token::Colon) {
1066 self.recover_missing_const_type(id, m)
1069 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1070 self.expect_semi()?;
1074 /// We were supposed to parse `:` but the `:` was missing.
1075 /// This means that the type is missing.
1076 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1077 // Construct the error and stash it away with the hope
1078 // that typeck will later enrich the error with a type.
1079 let kind = match m {
1080 Some(Mutability::Mut) => "static mut",
1081 Some(Mutability::Not) => "static",
1084 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1085 err.span_suggestion(
1087 "provide a type for the item",
1088 format!("{}: <type>", id),
1089 Applicability::HasPlaceholders,
1091 err.stash(id.span, StashKey::ItemNoType);
1093 // The user intended that the type be inferred,
1094 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1095 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None })
1098 /// Parses an enum declaration.
1099 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1100 let id = self.parse_ident()?;
1101 let mut generics = self.parse_generics()?;
1102 generics.where_clause = self.parse_where_clause()?;
1105 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1106 self.recover_stmt();
1110 let enum_definition =
1111 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1112 Ok((id, ItemKind::Enum(enum_definition, generics)))
1115 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1116 let variant_attrs = self.parse_outer_attributes()?;
1117 self.collect_tokens_trailing_token(
1120 |this, variant_attrs| {
1121 let vlo = this.token.span;
1123 let vis = this.parse_visibility(FollowedByType::No)?;
1124 if !this.recover_nested_adt_item(kw::Enum)? {
1125 return Ok((None, TrailingToken::None));
1127 let ident = this.parse_ident()?;
1129 let struct_def = if this.check(&token::OpenDelim(token::Brace)) {
1130 // Parse a struct variant.
1131 let (fields, recovered) = this.parse_record_struct_body()?;
1132 VariantData::Struct(fields, recovered)
1133 } else if this.check(&token::OpenDelim(token::Paren)) {
1134 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1136 VariantData::Unit(DUMMY_NODE_ID)
1140 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1142 let vr = ast::Variant {
1146 attrs: variant_attrs,
1149 span: vlo.to(this.prev_token.span),
1150 is_placeholder: false,
1153 Ok((Some(vr), TrailingToken::MaybeComma))
1158 /// Parses `struct Foo { ... }`.
1159 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1160 let class_name = self.parse_ident()?;
1162 let mut generics = self.parse_generics()?;
1164 // There is a special case worth noting here, as reported in issue #17904.
1165 // If we are parsing a tuple struct it is the case that the where clause
1166 // should follow the field list. Like so:
1168 // struct Foo<T>(T) where T: Copy;
1170 // If we are parsing a normal record-style struct it is the case
1171 // that the where clause comes before the body, and after the generics.
1172 // So if we look ahead and see a brace or a where-clause we begin
1173 // parsing a record style struct.
1175 // Otherwise if we look ahead and see a paren we parse a tuple-style
1178 let vdata = if self.token.is_keyword(kw::Where) {
1179 generics.where_clause = self.parse_where_clause()?;
1180 if self.eat(&token::Semi) {
1181 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1182 VariantData::Unit(DUMMY_NODE_ID)
1184 // If we see: `struct Foo<T> where T: Copy { ... }`
1185 let (fields, recovered) = self.parse_record_struct_body()?;
1186 VariantData::Struct(fields, recovered)
1188 // No `where` so: `struct Foo<T>;`
1189 } else if self.eat(&token::Semi) {
1190 VariantData::Unit(DUMMY_NODE_ID)
1191 // Record-style struct definition
1192 } else if self.token == token::OpenDelim(token::Brace) {
1193 let (fields, recovered) = self.parse_record_struct_body()?;
1194 VariantData::Struct(fields, recovered)
1195 // Tuple-style struct definition with optional where-clause.
1196 } else if self.token == token::OpenDelim(token::Paren) {
1197 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1198 generics.where_clause = self.parse_where_clause()?;
1199 self.expect_semi()?;
1202 let token_str = super::token_descr(&self.token);
1204 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1207 let mut err = self.struct_span_err(self.token.span, msg);
1208 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1212 Ok((class_name, ItemKind::Struct(vdata, generics)))
1215 /// Parses `union Foo { ... }`.
1216 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1217 let class_name = self.parse_ident()?;
1219 let mut generics = self.parse_generics()?;
1221 let vdata = if self.token.is_keyword(kw::Where) {
1222 generics.where_clause = self.parse_where_clause()?;
1223 let (fields, recovered) = self.parse_record_struct_body()?;
1224 VariantData::Struct(fields, recovered)
1225 } else if self.token == token::OpenDelim(token::Brace) {
1226 let (fields, recovered) = self.parse_record_struct_body()?;
1227 VariantData::Struct(fields, recovered)
1229 let token_str = super::token_descr(&self.token);
1230 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1231 let mut err = self.struct_span_err(self.token.span, msg);
1232 err.span_label(self.token.span, "expected `where` or `{` after union name");
1236 Ok((class_name, ItemKind::Union(vdata, generics)))
1239 fn parse_record_struct_body(&mut self) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1240 let mut fields = Vec::new();
1241 let mut recovered = false;
1242 if self.eat(&token::OpenDelim(token::Brace)) {
1243 while self.token != token::CloseDelim(token::Brace) {
1244 let field = self.parse_field_def().map_err(|e| {
1245 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1250 Ok(field) => fields.push(field),
1257 self.eat(&token::CloseDelim(token::Brace));
1259 let token_str = super::token_descr(&self.token);
1260 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1261 let mut err = self.struct_span_err(self.token.span, msg);
1262 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1266 Ok((fields, recovered))
1269 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1270 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1271 // Unit like structs are handled in parse_item_struct function
1272 self.parse_paren_comma_seq(|p| {
1273 let attrs = p.parse_outer_attributes()?;
1274 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1275 let lo = p.token.span;
1276 let vis = p.parse_visibility(FollowedByType::Yes)?;
1277 let ty = p.parse_ty()?;
1281 span: lo.to(ty.span),
1287 is_placeholder: false,
1289 TrailingToken::MaybeComma,
1296 /// Parses an element of a struct declaration.
1297 fn parse_field_def(&mut self) -> PResult<'a, FieldDef> {
1298 let attrs = self.parse_outer_attributes()?;
1299 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1300 let lo = this.token.span;
1301 let vis = this.parse_visibility(FollowedByType::No)?;
1302 Ok((this.parse_single_struct_field(lo, vis, attrs)?, TrailingToken::None))
1306 /// Parses a structure field declaration.
1307 fn parse_single_struct_field(
1311 attrs: Vec<Attribute>,
1312 ) -> PResult<'a, FieldDef> {
1313 let mut seen_comma: bool = false;
1314 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1315 if self.token == token::Comma {
1318 match self.token.kind {
1322 token::CloseDelim(token::Brace) => {}
1323 token::DocComment(..) => {
1324 let previous_span = self.prev_token.span;
1325 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1326 self.bump(); // consume the doc comment
1327 let comma_after_doc_seen = self.eat(&token::Comma);
1328 // `seen_comma` is always false, because we are inside doc block
1329 // condition is here to make code more readable
1330 if !seen_comma && comma_after_doc_seen {
1333 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1337 let sp = self.sess.source_map().next_point(previous_span);
1338 err.span_suggestion(
1340 "missing comma here",
1342 Applicability::MachineApplicable,
1349 let sp = self.prev_token.span.shrink_to_hi();
1350 let mut err = self.struct_span_err(
1352 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1355 // Try to recover extra trailing angle brackets
1356 let mut recovered = false;
1357 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1358 if let Some(last_segment) = segments.last() {
1359 recovered = self.check_trailing_angle_brackets(
1361 &[&token::Comma, &token::CloseDelim(token::Brace)],
1364 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1366 self.eat(&token::Comma);
1367 // `check_trailing_angle_brackets` already emitted a nicer error
1373 if self.token.is_ident() {
1374 // This is likely another field; emit the diagnostic and keep going
1375 err.span_suggestion(
1377 "try adding a comma",
1379 Applicability::MachineApplicable,
1386 // Make sure an error was emitted (either by recovering an angle bracket,
1387 // or by finding an identifier as the next token), since we're
1388 // going to continue parsing
1389 assert!(self.sess.span_diagnostic.has_errors());
1398 /// Parses a structure field.
1399 fn parse_name_and_ty(
1403 attrs: Vec<Attribute>,
1404 ) -> PResult<'a, FieldDef> {
1405 let name = self.parse_ident_common(false)?;
1406 self.expect(&token::Colon)?;
1407 let ty = self.parse_ty()?;
1409 span: lo.to(self.prev_token.span),
1415 is_placeholder: false,
1419 /// Parses a declarative macro 2.0 definition.
1420 /// The `macro` keyword has already been parsed.
1422 /// MacBody = "{" TOKEN_STREAM "}" ;
1423 /// MacParams = "(" TOKEN_STREAM ")" ;
1424 /// DeclMac = "macro" Ident MacParams? MacBody ;
1426 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1427 let ident = self.parse_ident()?;
1428 let body = if self.check(&token::OpenDelim(token::Brace)) {
1429 self.parse_mac_args()? // `MacBody`
1430 } else if self.check(&token::OpenDelim(token::Paren)) {
1431 let params = self.parse_token_tree(); // `MacParams`
1432 let pspan = params.span();
1433 if !self.check(&token::OpenDelim(token::Brace)) {
1434 return self.unexpected();
1436 let body = self.parse_token_tree(); // `MacBody`
1437 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1438 let bspan = body.span();
1439 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1440 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1441 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1442 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1444 return self.unexpected();
1447 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1448 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1451 /// Is this unambiguously the start of a `macro_rules! foo` item definition?
1452 fn is_macro_rules_item(&mut self) -> bool {
1453 self.check_keyword(kw::MacroRules)
1454 && self.look_ahead(1, |t| *t == token::Not)
1455 && self.look_ahead(2, |t| t.is_ident())
1458 /// Parses a `macro_rules! foo { ... }` declarative macro.
1459 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1460 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1461 self.expect(&token::Not)?; // `!`
1463 let ident = self.parse_ident()?;
1464 let body = self.parse_mac_args()?;
1465 self.eat_semi_for_macro_if_needed(&body);
1466 self.complain_if_pub_macro(vis, true);
1468 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1471 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1472 /// If that's not the case, emit an error.
1473 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1474 if let VisibilityKind::Inherited = vis.kind {
1478 let vstr = pprust::vis_to_string(vis);
1479 let vstr = vstr.trim_end();
1481 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1482 self.struct_span_err(vis.span, &msg)
1485 "try exporting the macro",
1486 "#[macro_export]".to_owned(),
1487 Applicability::MaybeIncorrect, // speculative
1491 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1494 "remove the visibility",
1496 Applicability::MachineApplicable,
1498 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1503 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1504 if args.need_semicolon() && !self.eat(&token::Semi) {
1505 self.report_invalid_macro_expansion_item(args);
1509 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1510 let span = args.span().expect("undelimited macro call");
1511 let mut err = self.struct_span_err(
1513 "macros that expand to items must be delimited with braces or followed by a semicolon",
1515 if self.unclosed_delims.is_empty() {
1516 let DelimSpan { open, close } = match args {
1517 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1518 MacArgs::Delimited(dspan, ..) => *dspan,
1520 err.multipart_suggestion(
1521 "change the delimiters to curly braces",
1522 vec![(open, "{".to_string()), (close, '}'.to_string())],
1523 Applicability::MaybeIncorrect,
1526 err.span_suggestion(
1528 "change the delimiters to curly braces",
1529 " { /* items */ }".to_string(),
1530 Applicability::HasPlaceholders,
1533 err.span_suggestion(
1534 span.shrink_to_hi(),
1537 Applicability::MaybeIncorrect,
1542 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1543 /// it is, we try to parse the item and report error about nested types.
1544 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1545 if (self.token.is_keyword(kw::Enum)
1546 || self.token.is_keyword(kw::Struct)
1547 || self.token.is_keyword(kw::Union))
1548 && self.look_ahead(1, |t| t.is_ident())
1550 let kw_token = self.token.clone();
1551 let kw_str = pprust::token_to_string(&kw_token);
1552 let item = self.parse_item(ForceCollect::No)?;
1554 self.struct_span_err(
1556 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1560 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1562 Applicability::MaybeIncorrect,
1565 // We successfully parsed the item but we must inform the caller about nested problem.
1572 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1574 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1575 type ReqName = fn(Edition) -> bool;
1577 /// Parsing of functions and methods.
1578 impl<'a> Parser<'a> {
1579 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1582 attrs: &mut Vec<Attribute>,
1585 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1586 let header = self.parse_fn_front_matter()?; // `const ... fn`
1587 let ident = self.parse_ident()?; // `foo`
1588 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1589 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1590 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1592 let mut sig_hi = self.prev_token.span;
1593 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi)?; // `;` or `{ ... }`.
1594 let fn_sig_span = sig_lo.to(sig_hi);
1595 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1598 /// Parse the "body" of a function.
1599 /// This can either be `;` when there's no body,
1600 /// or e.g. a block when the function is a provided one.
1603 attrs: &mut Vec<Attribute>,
1606 ) -> PResult<'a, Option<P<Block>>> {
1607 let (inner_attrs, body) = if self.eat(&token::Semi) {
1608 // Include the trailing semicolon in the span of the signature
1609 *sig_hi = self.prev_token.span;
1611 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1612 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1613 } else if self.token.kind == token::Eq {
1614 // Recover `fn foo() = $expr;`.
1616 let eq_sp = self.prev_token.span;
1617 let _ = self.parse_expr()?;
1618 self.expect_semi()?; // `;`
1619 let span = eq_sp.to(self.prev_token.span);
1620 self.struct_span_err(span, "function body cannot be `= expression;`")
1621 .multipart_suggestion(
1622 "surround the expression with `{` and `}` instead of `=` and `;`",
1623 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1624 Applicability::MachineApplicable,
1627 (Vec::new(), Some(self.mk_block_err(span)))
1629 if let Err(mut err) =
1630 self.expected_one_of_not_found(&[], &[token::Semi, token::OpenDelim(token::Brace)])
1632 if self.token.kind == token::CloseDelim(token::Brace) {
1633 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1634 // the AST for typechecking.
1635 err.span_label(ident.span, "while parsing this `fn`");
1645 attrs.extend(inner_attrs);
1649 /// Is the current token the start of an `FnHeader` / not a valid parse?
1651 /// `check_pub` adds additional `pub` to the checks in case users place it
1652 /// wrongly, can be used to ensure `pub` never comes after `default`.
1653 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
1654 // We use an over-approximation here.
1655 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1656 // `pub` is added in case users got confused with the ordering like `async pub fn`,
1657 // only if it wasn't preceeded by `default` as `default pub` is invalid.
1658 let quals: &[Symbol] = if check_pub {
1659 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1661 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1663 self.check_keyword(kw::Fn) // Definitely an `fn`.
1664 // `$qual fn` or `$qual $qual`:
1665 || quals.iter().any(|&kw| self.check_keyword(kw))
1666 && self.look_ahead(1, |t| {
1667 // `$qual fn`, e.g. `const fn` or `async fn`.
1668 t.is_keyword(kw::Fn)
1669 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1670 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
1671 // Rule out 2015 `const async: T = val`.
1673 // Rule out unsafe extern block.
1674 && !self.is_unsafe_foreign_mod())
1677 || self.check_keyword(kw::Extern)
1678 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1679 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1682 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1683 /// up to and including the `fn` keyword. The formal grammar is:
1686 /// Extern = "extern" StringLit? ;
1687 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1688 /// FnFrontMatter = FnQual "fn" ;
1690 pub(super) fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1691 let sp_start = self.token.span;
1692 let constness = self.parse_constness();
1693 let asyncness = self.parse_asyncness();
1694 let unsafety = self.parse_unsafety();
1695 let ext = self.parse_extern();
1697 if let Async::Yes { span, .. } = asyncness {
1698 self.ban_async_in_2015(span);
1701 if !self.eat_keyword(kw::Fn) {
1702 // It is possible for `expect_one_of` to recover given the contents of
1703 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1704 // account for this.
1705 match self.expect_one_of(&[], &[]) {
1707 Ok(false) => unreachable!(),
1709 // Recover incorrect visibility order such as `async pub`.
1710 if self.check_keyword(kw::Pub) {
1711 let sp = sp_start.to(self.prev_token.span);
1712 if let Ok(snippet) = self.span_to_snippet(sp) {
1713 let vis = self.parse_visibility(FollowedByType::No)?;
1714 let vs = pprust::vis_to_string(&vis);
1715 let vs = vs.trim_end();
1716 err.span_suggestion(
1717 sp_start.to(self.prev_token.span),
1718 &format!("visibility `{}` must come before `{}`", vs, snippet),
1719 format!("{} {}", vs, snippet),
1720 Applicability::MachineApplicable,
1729 Ok(FnHeader { constness, unsafety, asyncness, ext })
1732 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1733 fn ban_async_in_2015(&self, span: Span) {
1734 if span.rust_2015() {
1735 let diag = self.diagnostic();
1736 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
1737 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
1738 .help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION))
1739 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1744 /// Parses the parameter list and result type of a function declaration.
1745 pub(super) fn parse_fn_decl(
1748 ret_allow_plus: AllowPlus,
1749 recover_return_sign: RecoverReturnSign,
1750 ) -> PResult<'a, P<FnDecl>> {
1752 inputs: self.parse_fn_params(req_name)?,
1753 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
1757 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1758 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1759 let mut first_param = true;
1760 // Parse the arguments, starting out with `self` being allowed...
1761 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1762 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1764 let lo = p.prev_token.span;
1765 // Skip every token until next possible arg or end.
1766 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1767 // Create a placeholder argument for proper arg count (issue #34264).
1768 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
1770 // ...now that we've parsed the first argument, `self` is no longer allowed.
1771 first_param = false;
1774 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1775 self.deduplicate_recovered_params_names(&mut params);
1779 /// Parses a single function parameter.
1781 /// - `self` is syntactically allowed when `first_param` holds.
1782 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1783 let lo = self.token.span;
1784 let attrs = self.parse_outer_attributes()?;
1785 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1786 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1787 if let Some(mut param) = this.parse_self_param()? {
1788 param.attrs = attrs.into();
1789 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
1790 return Ok((res?, TrailingToken::None));
1793 let is_name_required = match this.token.kind {
1794 token::DotDotDot => false,
1795 _ => req_name(this.token.span.edition()),
1797 let (pat, ty) = if is_name_required || this.is_named_param() {
1798 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1800 let (pat, colon) = this.parse_fn_param_pat_colon()?;
1802 let mut err = this.unexpected::<()>().unwrap_err();
1803 return if let Some(ident) =
1804 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
1807 Ok((dummy_arg(ident), TrailingToken::None))
1813 this.eat_incorrect_doc_comment_for_param_type();
1814 (pat, this.parse_ty_for_param()?)
1816 debug!("parse_param_general ident_to_pat");
1817 let parser_snapshot_before_ty = this.clone();
1818 this.eat_incorrect_doc_comment_for_param_type();
1819 let mut ty = this.parse_ty_for_param();
1821 && this.token != token::Comma
1822 && this.token != token::CloseDelim(token::Paren)
1824 // This wasn't actually a type, but a pattern looking like a type,
1825 // so we are going to rollback and re-parse for recovery.
1826 ty = this.unexpected();
1830 let ident = Ident::new(kw::Empty, this.prev_token.span);
1831 let bm = BindingMode::ByValue(Mutability::Not);
1832 let pat = this.mk_pat_ident(ty.span, bm, ident);
1835 // If this is a C-variadic argument and we hit an error, return the error.
1836 Err(err) if this.token == token::DotDotDot => return Err(err),
1837 // Recover from attempting to parse the argument as a type without pattern.
1840 *this = parser_snapshot_before_ty;
1841 this.recover_arg_parse()?
1846 let span = lo.until(this.token.span);
1850 attrs: attrs.into(),
1851 id: ast::DUMMY_NODE_ID,
1852 is_placeholder: false,
1857 TrailingToken::None,
1862 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1863 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1864 // Extract an identifier *after* having confirmed that the token is one.
1865 let expect_self_ident = |this: &mut Self| match this.token.ident() {
1866 Some((ident, false)) => {
1870 _ => unreachable!(),
1872 // Is `self` `n` tokens ahead?
1873 let is_isolated_self = |this: &Self, n| {
1874 this.is_keyword_ahead(n, &[kw::SelfLower])
1875 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1877 // Is `mut self` `n` tokens ahead?
1878 let is_isolated_mut_self =
1879 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1880 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1881 let parse_self_possibly_typed = |this: &mut Self, m| {
1882 let eself_ident = expect_self_ident(this);
1883 let eself_hi = this.prev_token.span;
1884 let eself = if this.eat(&token::Colon) {
1885 SelfKind::Explicit(this.parse_ty()?, m)
1889 Ok((eself, eself_ident, eself_hi))
1891 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1892 let recover_self_ptr = |this: &mut Self| {
1893 let msg = "cannot pass `self` by raw pointer";
1894 let span = this.token.span;
1895 this.struct_span_err(span, msg).span_label(span, msg).emit();
1897 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
1900 // Parse optional `self` parameter of a method.
1901 // Only a limited set of initial token sequences is considered `self` parameters; anything
1902 // else is parsed as a normal function parameter list, so some lookahead is required.
1903 let eself_lo = self.token.span;
1904 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
1905 token::BinOp(token::And) => {
1906 let eself = if is_isolated_self(self, 1) {
1909 SelfKind::Region(None, Mutability::Not)
1910 } else if is_isolated_mut_self(self, 1) {
1914 SelfKind::Region(None, Mutability::Mut)
1915 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1918 let lt = self.expect_lifetime();
1919 SelfKind::Region(Some(lt), Mutability::Not)
1920 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1923 let lt = self.expect_lifetime();
1925 SelfKind::Region(Some(lt), Mutability::Mut)
1930 (eself, expect_self_ident(self), self.prev_token.span)
1933 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1935 recover_self_ptr(self)?
1937 // `*mut self` and `*const self`
1938 token::BinOp(token::Star)
1939 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1943 recover_self_ptr(self)?
1945 // `self` and `self: TYPE`
1946 token::Ident(..) if is_isolated_self(self, 0) => {
1947 parse_self_possibly_typed(self, Mutability::Not)?
1949 // `mut self` and `mut self: TYPE`
1950 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1952 parse_self_possibly_typed(self, Mutability::Mut)?
1954 _ => return Ok(None),
1957 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1958 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1961 fn is_named_param(&self) -> bool {
1962 let offset = match self.token.kind {
1963 token::Interpolated(ref nt) => match **nt {
1964 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1967 token::BinOp(token::And) | token::AndAnd => 1,
1968 _ if self.token.is_keyword(kw::Mut) => 1,
1972 self.look_ahead(offset, |t| t.is_ident())
1973 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1976 fn recover_first_param(&mut self) -> &'static str {
1978 .parse_outer_attributes()
1979 .and_then(|_| self.parse_self_param())
1980 .map_err(|mut e| e.cancel())
1982 Ok(Some(_)) => "method",