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_field_ident("enum", vlo)?;
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("struct")?;
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("struct")?;
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("struct")?;
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("union")?;
1224 VariantData::Struct(fields, recovered)
1225 } else if self.token == token::OpenDelim(token::Brace) {
1226 let (fields, recovered) = self.parse_record_struct_body("union")?;
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 pub(super) fn parse_record_struct_body(
1242 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1243 let mut fields = Vec::new();
1244 let mut recovered = false;
1245 if self.eat(&token::OpenDelim(token::Brace)) {
1246 while self.token != token::CloseDelim(token::Brace) {
1247 let field = self.parse_field_def(adt_ty).map_err(|e| {
1248 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1253 Ok(field) => fields.push(field),
1260 self.eat(&token::CloseDelim(token::Brace));
1262 let token_str = super::token_descr(&self.token);
1263 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1264 let mut err = self.struct_span_err(self.token.span, msg);
1265 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1269 Ok((fields, recovered))
1272 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1273 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1274 // Unit like structs are handled in parse_item_struct function
1275 self.parse_paren_comma_seq(|p| {
1276 let attrs = p.parse_outer_attributes()?;
1277 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1278 let lo = p.token.span;
1279 let vis = p.parse_visibility(FollowedByType::Yes)?;
1280 let ty = p.parse_ty()?;
1284 span: lo.to(ty.span),
1290 is_placeholder: false,
1292 TrailingToken::MaybeComma,
1299 /// Parses an element of a struct declaration.
1300 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1301 let attrs = self.parse_outer_attributes()?;
1302 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1303 let lo = this.token.span;
1304 let vis = this.parse_visibility(FollowedByType::No)?;
1305 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1309 /// Parses a structure field declaration.
1310 fn parse_single_struct_field(
1315 attrs: Vec<Attribute>,
1316 ) -> PResult<'a, FieldDef> {
1317 let mut seen_comma: bool = false;
1318 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1319 if self.token == token::Comma {
1322 match self.token.kind {
1326 token::CloseDelim(token::Brace) => {}
1327 token::DocComment(..) => {
1328 let previous_span = self.prev_token.span;
1329 let mut err = self.span_err(self.token.span, Error::UselessDocComment);
1330 self.bump(); // consume the doc comment
1331 let comma_after_doc_seen = self.eat(&token::Comma);
1332 // `seen_comma` is always false, because we are inside doc block
1333 // condition is here to make code more readable
1334 if !seen_comma && comma_after_doc_seen {
1337 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1341 let sp = self.sess.source_map().next_point(previous_span);
1342 err.span_suggestion(
1344 "missing comma here",
1346 Applicability::MachineApplicable,
1353 let sp = self.prev_token.span.shrink_to_hi();
1354 let mut err = self.struct_span_err(
1356 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1359 // Try to recover extra trailing angle brackets
1360 let mut recovered = false;
1361 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1362 if let Some(last_segment) = segments.last() {
1363 recovered = self.check_trailing_angle_brackets(
1365 &[&token::Comma, &token::CloseDelim(token::Brace)],
1368 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1370 self.eat(&token::Comma);
1371 // `check_trailing_angle_brackets` already emitted a nicer error
1377 if self.token.is_ident() {
1378 // This is likely another field; emit the diagnostic and keep going
1379 err.span_suggestion(
1381 "try adding a comma",
1383 Applicability::MachineApplicable,
1390 // Make sure an error was emitted (either by recovering an angle bracket,
1391 // or by finding an identifier as the next token), since we're
1392 // going to continue parsing
1393 assert!(self.sess.span_diagnostic.has_errors());
1402 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1403 if let Err(mut err) = self.expect(&token::Colon) {
1404 let sm = self.sess.source_map();
1405 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1406 let semi_typo = self.token.kind == token::Semi
1407 && self.look_ahead(1, |t| {
1409 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1410 // when there's no type and `;` was used instead of a comma.
1411 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1412 (Ok(l), Ok(r)) => l.line == r.line,
1416 if eq_typo || semi_typo {
1418 // Gracefully handle small typos.
1419 err.span_suggestion_short(
1420 self.prev_token.span,
1421 "field names and their types are separated with `:`",
1423 Applicability::MachineApplicable,
1433 /// Parses a structure field.
1434 fn parse_name_and_ty(
1439 attrs: Vec<Attribute>,
1440 ) -> PResult<'a, FieldDef> {
1441 let name = self.parse_field_ident(adt_ty, lo)?;
1442 self.expect_field_ty_separator()?;
1443 let ty = self.parse_ty()?;
1444 if self.token.kind == token::Eq {
1446 let const_expr = self.parse_anon_const_expr()?;
1447 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1448 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1451 "remove this unsupported default value",
1453 Applicability::MachineApplicable,
1458 span: lo.to(self.prev_token.span),
1464 is_placeholder: false,
1468 /// Parses a field identifier. Specialized version of `parse_ident_common`
1469 /// for better diagnostics and suggestions.
1470 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1471 let (ident, is_raw) = self.ident_or_err()?;
1472 if !is_raw && ident.is_reserved() {
1473 if ident.name == kw::Underscore {
1474 self.sess.gated_spans.gate(sym::unnamed_fields, lo);
1476 let err = if self.check_fn_front_matter(false) {
1477 let _ = self.parse_fn(&mut Vec::new(), |_| true, lo);
1478 let mut err = self.struct_span_err(
1479 lo.to(self.prev_token.span),
1480 &format!("functions are not allowed in {} definitions", adt_ty),
1483 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1485 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1488 self.expected_ident_found()
1497 /// Parses a declarative macro 2.0 definition.
1498 /// The `macro` keyword has already been parsed.
1500 /// MacBody = "{" TOKEN_STREAM "}" ;
1501 /// MacParams = "(" TOKEN_STREAM ")" ;
1502 /// DeclMac = "macro" Ident MacParams? MacBody ;
1504 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1505 let ident = self.parse_ident()?;
1506 let body = if self.check(&token::OpenDelim(token::Brace)) {
1507 self.parse_mac_args()? // `MacBody`
1508 } else if self.check(&token::OpenDelim(token::Paren)) {
1509 let params = self.parse_token_tree(); // `MacParams`
1510 let pspan = params.span();
1511 if !self.check(&token::OpenDelim(token::Brace)) {
1512 return self.unexpected();
1514 let body = self.parse_token_tree(); // `MacBody`
1515 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1516 let bspan = body.span();
1517 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1518 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1519 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1520 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1522 return self.unexpected();
1525 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1526 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1529 /// Is this unambiguously the start of a `macro_rules! foo` item definition?
1530 fn is_macro_rules_item(&mut self) -> bool {
1531 self.check_keyword(kw::MacroRules)
1532 && self.look_ahead(1, |t| *t == token::Not)
1533 && self.look_ahead(2, |t| t.is_ident())
1536 /// Parses a `macro_rules! foo { ... }` declarative macro.
1537 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1538 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1539 self.expect(&token::Not)?; // `!`
1541 let ident = self.parse_ident()?;
1542 let body = self.parse_mac_args()?;
1543 self.eat_semi_for_macro_if_needed(&body);
1544 self.complain_if_pub_macro(vis, true);
1546 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1549 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1550 /// If that's not the case, emit an error.
1551 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1552 if let VisibilityKind::Inherited = vis.kind {
1556 let vstr = pprust::vis_to_string(vis);
1557 let vstr = vstr.trim_end();
1559 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1560 self.struct_span_err(vis.span, &msg)
1563 "try exporting the macro",
1564 "#[macro_export]".to_owned(),
1565 Applicability::MaybeIncorrect, // speculative
1569 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1572 "remove the visibility",
1574 Applicability::MachineApplicable,
1576 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1581 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1582 if args.need_semicolon() && !self.eat(&token::Semi) {
1583 self.report_invalid_macro_expansion_item(args);
1587 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1588 let span = args.span().expect("undelimited macro call");
1589 let mut err = self.struct_span_err(
1591 "macros that expand to items must be delimited with braces or followed by a semicolon",
1593 if self.unclosed_delims.is_empty() {
1594 let DelimSpan { open, close } = match args {
1595 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1596 MacArgs::Delimited(dspan, ..) => *dspan,
1598 err.multipart_suggestion(
1599 "change the delimiters to curly braces",
1600 vec![(open, "{".to_string()), (close, '}'.to_string())],
1601 Applicability::MaybeIncorrect,
1604 err.span_suggestion(
1606 "change the delimiters to curly braces",
1607 " { /* items */ }".to_string(),
1608 Applicability::HasPlaceholders,
1611 err.span_suggestion(
1612 span.shrink_to_hi(),
1615 Applicability::MaybeIncorrect,
1620 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1621 /// it is, we try to parse the item and report error about nested types.
1622 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1623 if (self.token.is_keyword(kw::Enum)
1624 || self.token.is_keyword(kw::Struct)
1625 || self.token.is_keyword(kw::Union))
1626 && self.look_ahead(1, |t| t.is_ident())
1628 let kw_token = self.token.clone();
1629 let kw_str = pprust::token_to_string(&kw_token);
1630 let item = self.parse_item(ForceCollect::No)?;
1632 self.struct_span_err(
1634 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1638 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1640 Applicability::MaybeIncorrect,
1643 // We successfully parsed the item but we must inform the caller about nested problem.
1650 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1652 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1653 type ReqName = fn(Edition) -> bool;
1655 /// Parsing of functions and methods.
1656 impl<'a> Parser<'a> {
1657 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1660 attrs: &mut Vec<Attribute>,
1663 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1664 let header = self.parse_fn_front_matter()?; // `const ... fn`
1665 let ident = self.parse_ident()?; // `foo`
1666 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1667 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1668 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1670 let mut sig_hi = self.prev_token.span;
1671 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi)?; // `;` or `{ ... }`.
1672 let fn_sig_span = sig_lo.to(sig_hi);
1673 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1676 /// Parse the "body" of a function.
1677 /// This can either be `;` when there's no body,
1678 /// or e.g. a block when the function is a provided one.
1681 attrs: &mut Vec<Attribute>,
1684 ) -> PResult<'a, Option<P<Block>>> {
1685 let (inner_attrs, body) = if self.eat(&token::Semi) {
1686 // Include the trailing semicolon in the span of the signature
1687 *sig_hi = self.prev_token.span;
1689 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1690 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1691 } else if self.token.kind == token::Eq {
1692 // Recover `fn foo() = $expr;`.
1694 let eq_sp = self.prev_token.span;
1695 let _ = self.parse_expr()?;
1696 self.expect_semi()?; // `;`
1697 let span = eq_sp.to(self.prev_token.span);
1698 self.struct_span_err(span, "function body cannot be `= expression;`")
1699 .multipart_suggestion(
1700 "surround the expression with `{` and `}` instead of `=` and `;`",
1701 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1702 Applicability::MachineApplicable,
1705 (Vec::new(), Some(self.mk_block_err(span)))
1707 if let Err(mut err) =
1708 self.expected_one_of_not_found(&[], &[token::Semi, token::OpenDelim(token::Brace)])
1710 if self.token.kind == token::CloseDelim(token::Brace) {
1711 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1712 // the AST for typechecking.
1713 err.span_label(ident.span, "while parsing this `fn`");
1723 attrs.extend(inner_attrs);
1727 /// Is the current token the start of an `FnHeader` / not a valid parse?
1729 /// `check_pub` adds additional `pub` to the checks in case users place it
1730 /// wrongly, can be used to ensure `pub` never comes after `default`.
1731 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
1732 // We use an over-approximation here.
1733 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1734 // `pub` is added in case users got confused with the ordering like `async pub fn`,
1735 // only if it wasn't preceeded by `default` as `default pub` is invalid.
1736 let quals: &[Symbol] = if check_pub {
1737 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1739 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1741 self.check_keyword(kw::Fn) // Definitely an `fn`.
1742 // `$qual fn` or `$qual $qual`:
1743 || quals.iter().any(|&kw| self.check_keyword(kw))
1744 && self.look_ahead(1, |t| {
1745 // `$qual fn`, e.g. `const fn` or `async fn`.
1746 t.is_keyword(kw::Fn)
1747 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1748 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
1749 // Rule out 2015 `const async: T = val`.
1751 // Rule out unsafe extern block.
1752 && !self.is_unsafe_foreign_mod())
1755 || self.check_keyword(kw::Extern)
1756 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1757 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1760 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1761 /// up to and including the `fn` keyword. The formal grammar is:
1764 /// Extern = "extern" StringLit? ;
1765 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1766 /// FnFrontMatter = FnQual "fn" ;
1768 pub(super) fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1769 let sp_start = self.token.span;
1770 let constness = self.parse_constness();
1771 let asyncness = self.parse_asyncness();
1772 let unsafety = self.parse_unsafety();
1773 let ext = self.parse_extern();
1775 if let Async::Yes { span, .. } = asyncness {
1776 self.ban_async_in_2015(span);
1779 if !self.eat_keyword(kw::Fn) {
1780 // It is possible for `expect_one_of` to recover given the contents of
1781 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1782 // account for this.
1783 match self.expect_one_of(&[], &[]) {
1785 Ok(false) => unreachable!(),
1787 // Recover incorrect visibility order such as `async pub`.
1788 if self.check_keyword(kw::Pub) {
1789 let sp = sp_start.to(self.prev_token.span);
1790 if let Ok(snippet) = self.span_to_snippet(sp) {
1791 let vis = self.parse_visibility(FollowedByType::No)?;
1792 let vs = pprust::vis_to_string(&vis);
1793 let vs = vs.trim_end();
1794 err.span_suggestion(
1795 sp_start.to(self.prev_token.span),
1796 &format!("visibility `{}` must come before `{}`", vs, snippet),
1797 format!("{} {}", vs, snippet),
1798 Applicability::MachineApplicable,
1807 Ok(FnHeader { constness, unsafety, asyncness, ext })
1810 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1811 fn ban_async_in_2015(&self, span: Span) {
1812 if span.rust_2015() {
1813 let diag = self.diagnostic();
1814 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
1815 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
1816 .help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION))
1817 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1822 /// Parses the parameter list and result type of a function declaration.
1823 pub(super) fn parse_fn_decl(
1826 ret_allow_plus: AllowPlus,
1827 recover_return_sign: RecoverReturnSign,
1828 ) -> PResult<'a, P<FnDecl>> {
1830 inputs: self.parse_fn_params(req_name)?,
1831 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
1835 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1836 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1837 let mut first_param = true;
1838 // Parse the arguments, starting out with `self` being allowed...
1839 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1840 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1842 let lo = p.prev_token.span;
1843 // Skip every token until next possible arg or end.
1844 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1845 // Create a placeholder argument for proper arg count (issue #34264).
1846 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
1848 // ...now that we've parsed the first argument, `self` is no longer allowed.
1849 first_param = false;
1852 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1853 self.deduplicate_recovered_params_names(&mut params);
1857 /// Parses a single function parameter.
1859 /// - `self` is syntactically allowed when `first_param` holds.
1860 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1861 let lo = self.token.span;
1862 let attrs = self.parse_outer_attributes()?;
1863 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1864 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1865 if let Some(mut param) = this.parse_self_param()? {
1866 param.attrs = attrs.into();
1867 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
1868 return Ok((res?, TrailingToken::None));
1871 let is_name_required = match this.token.kind {
1872 token::DotDotDot => false,
1873 _ => req_name(this.token.span.edition()),
1875 let (pat, ty) = if is_name_required || this.is_named_param() {
1876 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1878 let (pat, colon) = this.parse_fn_param_pat_colon()?;
1880 let mut err = this.unexpected::<()>().unwrap_err();
1881 return if let Some(ident) =
1882 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
1885 Ok((dummy_arg(ident), TrailingToken::None))
1891 this.eat_incorrect_doc_comment_for_param_type();
1892 (pat, this.parse_ty_for_param()?)
1894 debug!("parse_param_general ident_to_pat");
1895 let parser_snapshot_before_ty = this.clone();
1896 this.eat_incorrect_doc_comment_for_param_type();
1897 let mut ty = this.parse_ty_for_param();
1899 && this.token != token::Comma
1900 && this.token != token::CloseDelim(token::Paren)
1902 // This wasn't actually a type, but a pattern looking like a type,
1903 // so we are going to rollback and re-parse for recovery.
1904 ty = this.unexpected();
1908 let ident = Ident::new(kw::Empty, this.prev_token.span);
1909 let bm = BindingMode::ByValue(Mutability::Not);
1910 let pat = this.mk_pat_ident(ty.span, bm, ident);
1913 // If this is a C-variadic argument and we hit an error, return the error.
1914 Err(err) if this.token == token::DotDotDot => return Err(err),
1915 // Recover from attempting to parse the argument as a type without pattern.
1918 *this = parser_snapshot_before_ty;
1919 this.recover_arg_parse()?
1924 let span = lo.until(this.token.span);
1928 attrs: attrs.into(),
1929 id: ast::DUMMY_NODE_ID,
1930 is_placeholder: false,
1935 TrailingToken::None,
1940 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1941 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1942 // Extract an identifier *after* having confirmed that the token is one.
1943 let expect_self_ident = |this: &mut Self| match this.token.ident() {
1944 Some((ident, false)) => {
1948 _ => unreachable!(),
1950 // Is `self` `n` tokens ahead?
1951 let is_isolated_self = |this: &Self, n| {
1952 this.is_keyword_ahead(n, &[kw::SelfLower])
1953 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1955 // Is `mut self` `n` tokens ahead?
1956 let is_isolated_mut_self =
1957 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1958 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1959 let parse_self_possibly_typed = |this: &mut Self, m| {
1960 let eself_ident = expect_self_ident(this);
1961 let eself_hi = this.prev_token.span;
1962 let eself = if this.eat(&token::Colon) {
1963 SelfKind::Explicit(this.parse_ty()?, m)
1967 Ok((eself, eself_ident, eself_hi))
1969 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1970 let recover_self_ptr = |this: &mut Self| {
1971 let msg = "cannot pass `self` by raw pointer";
1972 let span = this.token.span;
1973 this.struct_span_err(span, msg).span_label(span, msg).emit();
1975 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
1978 // Parse optional `self` parameter of a method.
1979 // Only a limited set of initial token sequences is considered `self` parameters; anything
1980 // else is parsed as a normal function parameter list, so some lookahead is required.
1981 let eself_lo = self.token.span;
1982 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
1983 token::BinOp(token::And) => {
1984 let eself = if is_isolated_self(self, 1) {
1987 SelfKind::Region(None, Mutability::Not)
1988 } else if is_isolated_mut_self(self, 1) {
1992 SelfKind::Region(None, Mutability::Mut)
1993 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1996 let lt = self.expect_lifetime();
1997 SelfKind::Region(Some(lt), Mutability::Not)
1998 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2001 let lt = self.expect_lifetime();
2003 SelfKind::Region(Some(lt), Mutability::Mut)
2008 (eself, expect_self_ident(self), self.prev_token.span)
2011 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2013 recover_self_ptr(self)?
2015 // `*mut self` and `*const self`
2016 token::BinOp(token::Star)
2017 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2021 recover_self_ptr(self)?
2023 // `self` and `self: TYPE`
2024 token::Ident(..) if is_isolated_self(self, 0) => {
2025 parse_self_possibly_typed(self, Mutability::Not)?
2027 // `mut self` and `mut self: TYPE`
2028 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2030 parse_self_possibly_typed(self, Mutability::Mut)?
2032 _ => return Ok(None),
2035 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2036 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2039 fn is_named_param(&self) -> bool {
2040 let offset = match self.token.kind {
2041 token::Interpolated(ref nt) => match **nt {
2042 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2045 token::BinOp(token::And) | token::AndAnd => 1,
2046 _ if self.token.is_keyword(kw::Mut) => 1,
2050 self.look_ahead(offset, |t| t.is_ident())
2051 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2054 fn recover_first_param(&mut self) -> &'static str {
2056 .parse_outer_attributes()
2057 .and_then(|_| self.parse_self_param())
2058 .map_err(|mut e| e.cancel())
2060 Ok(Some(_)) => "method",