1 use crate::errors::{DocCommentDoesNotDocumentAnything, UseEmptyBlockNotSemi};
3 use super::diagnostics::{dummy_arg, ConsumeClosingDelim};
4 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
5 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
8 use rustc_ast::token::{self, Delimiter, TokenKind};
9 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
10 use rustc_ast::util::case::Case;
11 use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
12 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
13 use rustc_ast::{BindingAnnotation, Block, FnDecl, FnSig, Param, SelfKind};
14 use rustc_ast::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData};
15 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
16 use rustc_ast::{MacCall, MacDelimiter};
17 use rustc_ast_pretty::pprust;
18 use rustc_errors::{struct_span_err, Applicability, IntoDiagnostic, PResult, StashKey};
19 use rustc_span::edition::Edition;
20 use rustc_span::lev_distance::lev_distance;
21 use rustc_span::source_map::{self, Span};
22 use rustc_span::symbol::{kw, sym, Ident, Symbol};
23 use rustc_span::DUMMY_SP;
24 use std::convert::TryFrom;
26 use thin_vec::ThinVec;
30 /// Parses a source module as a crate. This is the main entry point for the parser.
31 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
32 let (attrs, items, spans) = self.parse_mod(&token::Eof)?;
33 Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
36 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
37 fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemInfo> {
38 let unsafety = self.parse_unsafety(Case::Sensitive);
39 self.expect_keyword(kw::Mod)?;
40 let id = self.parse_ident()?;
41 let mod_kind = if self.eat(&token::Semi) {
44 self.expect(&token::OpenDelim(Delimiter::Brace))?;
45 let (inner_attrs, items, inner_span) =
46 self.parse_mod(&token::CloseDelim(Delimiter::Brace))?;
47 attrs.extend(inner_attrs);
48 ModKind::Loaded(items, Inline::Yes, inner_span)
50 Ok((id, ItemKind::Mod(unsafety, mod_kind)))
53 /// Parses the contents of a module (inner attributes followed by module items).
57 ) -> PResult<'a, (AttrVec, Vec<P<Item>>, ModSpans)> {
58 let lo = self.token.span;
59 let attrs = self.parse_inner_attributes()?;
61 let post_attr_lo = self.token.span;
62 let mut items = vec![];
63 while let Some(item) = self.parse_item(ForceCollect::No)? {
65 self.maybe_consume_incorrect_semicolon(&items);
69 let token_str = super::token_descr(&self.token);
70 if !self.maybe_consume_incorrect_semicolon(&items) {
71 let msg = &format!("expected item, found {token_str}");
72 let mut err = self.struct_span_err(self.token.span, msg);
73 let label = if self.is_kw_followed_by_ident(kw::Let) {
74 "consider using `const` or `static` instead of `let` for global variables"
78 err.span_label(self.token.span, label);
83 let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
84 let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
85 Ok((attrs, items, mod_spans))
89 pub(super) type ItemInfo = (Ident, ItemKind);
92 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
93 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
94 self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
99 fn_parse_mode: FnParseMode,
100 force_collect: ForceCollect,
101 ) -> PResult<'a, Option<Item>> {
102 let attrs = self.parse_outer_attributes()?;
103 self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
106 pub(super) fn parse_item_common(
111 fn_parse_mode: FnParseMode,
112 force_collect: ForceCollect,
113 ) -> PResult<'a, Option<Item>> {
114 // Don't use `maybe_whole` so that we have precise control
115 // over when we bump the parser
116 if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
117 let mut item = item.clone();
120 attrs.prepend_to_nt_inner(&mut item.attrs);
121 return Ok(Some(item.into_inner()));
124 let mut unclosed_delims = vec![];
126 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
128 this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
129 unclosed_delims.append(&mut this.unclosed_delims);
130 Ok((item?, TrailingToken::None))
133 self.unclosed_delims.append(&mut unclosed_delims);
137 fn parse_item_common_(
142 fn_parse_mode: FnParseMode,
143 ) -> PResult<'a, Option<Item>> {
144 let lo = self.token.span;
145 let vis = self.parse_visibility(FollowedByType::No)?;
146 let mut def = self.parse_defaultness();
147 let kind = self.parse_item_kind(
156 if let Some((ident, kind)) = kind {
157 self.error_on_unconsumed_default(def, &kind);
158 let span = lo.to(self.prev_token.span);
159 let id = DUMMY_NODE_ID;
160 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
161 return Ok(Some(item));
164 // At this point, we have failed to parse an item.
165 self.error_on_unmatched_vis(&vis);
166 self.error_on_unmatched_defaultness(def);
168 self.recover_attrs_no_item(&attrs)?;
173 /// Error in-case a non-inherited visibility was parsed but no item followed.
174 fn error_on_unmatched_vis(&self, vis: &Visibility) {
175 if let VisibilityKind::Inherited = vis.kind {
178 let vs = pprust::vis_to_string(&vis);
179 let vs = vs.trim_end();
180 self.struct_span_err(vis.span, &format!("visibility `{vs}` is not followed by an item"))
181 .span_label(vis.span, "the visibility")
182 .help(&format!("you likely meant to define an item, e.g., `{vs} fn foo() {{}}`"))
186 /// Error in-case a `default` was parsed but no item followed.
187 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
188 if let Defaultness::Default(sp) = def {
189 self.struct_span_err(sp, "`default` is not followed by an item")
190 .span_label(sp, "the `default` qualifier")
191 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
196 /// Error in-case `default` was parsed in an in-appropriate context.
197 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
198 if let Defaultness::Default(span) = def {
199 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
200 self.struct_span_err(span, &msg)
201 .span_label(span, "`default` because of this")
202 .note("only associated `fn`, `const`, and `type` items can be `default`")
207 /// Parses one of the items allowed by the flags.
211 macros_allowed: bool,
214 def: &mut Defaultness,
215 fn_parse_mode: FnParseMode,
217 ) -> PResult<'a, Option<ItemInfo>> {
218 let def_final = def == &Defaultness::Final;
219 let mut def_ = || mem::replace(def, Defaultness::Final);
221 let info = if self.eat_keyword_case(kw::Use, case) {
222 self.parse_use_item()?
223 } else if self.check_fn_front_matter(def_final, case) {
225 let (ident, sig, generics, body) = self.parse_fn(attrs, fn_parse_mode, lo, vis)?;
226 (ident, ItemKind::Fn(Box::new(Fn { defaultness: def_(), sig, generics, body })))
227 } else if self.eat_keyword(kw::Extern) {
228 if self.eat_keyword(kw::Crate) {
230 self.parse_item_extern_crate()?
233 self.parse_item_foreign_mod(attrs, Unsafe::No)?
235 } else if self.is_unsafe_foreign_mod() {
237 let unsafety = self.parse_unsafety(Case::Sensitive);
238 self.expect_keyword(kw::Extern)?;
239 self.parse_item_foreign_mod(attrs, unsafety)?
240 } else if self.is_static_global() {
242 self.bump(); // `static`
243 let m = self.parse_mutability();
244 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
245 (ident, ItemKind::Static(ty, m, expr))
246 } else if let Const::Yes(const_span) = self.parse_constness(Case::Sensitive) {
248 if self.token.is_keyword(kw::Impl) {
249 // recover from `const impl`, suggest `impl const`
250 self.recover_const_impl(const_span, attrs, def_())?
252 self.recover_const_mut(const_span);
253 let (ident, ty, expr) = self.parse_item_global(None)?;
254 (ident, ItemKind::Const(def_(), ty, expr))
256 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
258 self.parse_item_trait(attrs, lo)?
259 } else if self.check_keyword(kw::Impl)
260 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
263 self.parse_item_impl(attrs, def_())?
264 } else if self.check_keyword(kw::Mod)
265 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
268 self.parse_item_mod(attrs)?
269 } else if self.eat_keyword(kw::Type) {
271 self.parse_type_alias(def_())?
272 } else if self.eat_keyword(kw::Enum) {
274 self.parse_item_enum()?
275 } else if self.eat_keyword(kw::Struct) {
277 self.parse_item_struct()?
278 } else if self.is_kw_followed_by_ident(kw::Union) {
280 self.bump(); // `union`
281 self.parse_item_union()?
282 } else if self.eat_keyword(kw::Macro) {
284 self.parse_item_decl_macro(lo)?
285 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
287 self.parse_item_macro_rules(vis, has_bang)?
288 } else if self.isnt_macro_invocation()
289 && (self.token.is_ident_named(sym::import)
290 || self.token.is_ident_named(sym::using)
291 || self.token.is_ident_named(sym::include)
292 || self.token.is_ident_named(sym::require))
294 return self.recover_import_as_use();
295 } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
296 self.recover_missing_kw_before_item()?;
298 } else if self.isnt_macro_invocation() && case == Case::Sensitive {
301 // Recover wrong cased keywords
302 return self.parse_item_kind(
311 } else if macros_allowed && self.check_path() {
312 // MACRO INVOCATION ITEM
313 (Ident::empty(), ItemKind::MacCall(P(self.parse_item_macro(vis)?)))
320 fn recover_import_as_use(&mut self) -> PResult<'a, Option<(Ident, ItemKind)>> {
321 let span = self.token.span;
322 let token_name = super::token_descr(&self.token);
323 let snapshot = self.create_snapshot_for_diagnostic();
325 match self.parse_use_item() {
327 self.struct_span_err(span, format!("expected item, found {token_name}"))
328 .span_suggestion_short(
330 "items are imported using the `use` keyword",
332 Applicability::MachineApplicable,
339 self.restore_snapshot(snapshot);
345 fn parse_use_item(&mut self) -> PResult<'a, (Ident, ItemKind)> {
346 let tree = self.parse_use_tree()?;
347 if let Err(mut e) = self.expect_semi() {
349 UseTreeKind::Glob => {
350 e.note("the wildcard token must be last on the path");
352 UseTreeKind::Nested(..) => {
353 e.note("glob-like brace syntax must be last on the path");
359 Ok((Ident::empty(), ItemKind::Use(tree)))
362 /// When parsing a statement, would the start of a path be an item?
363 pub(super) fn is_path_start_item(&mut self) -> bool {
364 self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
365 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
366 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
367 || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
370 /// Are we sure this could not possibly be a macro invocation?
371 fn isnt_macro_invocation(&mut self) -> bool {
372 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
375 /// Recover on encountering a struct or method definition where the user
376 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
377 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
378 // Space between `pub` keyword and the identifier
381 // ^^^ `sp` points here
382 let sp = self.prev_token.span.between(self.token.span);
383 let full_sp = self.prev_token.span.to(self.token.span);
384 let ident_sp = self.token.span;
385 if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace)) {
386 // possible public struct definition where `struct` was forgotten
387 let ident = self.parse_ident().unwrap();
388 let msg = format!("add `struct` here to parse `{ident}` as a public struct");
389 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
390 err.span_suggestion_short(
394 Applicability::MaybeIncorrect, // speculative
397 } else if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Parenthesis)) {
398 let ident = self.parse_ident().unwrap();
400 let kw_name = self.recover_first_param();
401 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::Yes);
402 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
403 self.eat_to_tokens(&[&token::OpenDelim(Delimiter::Brace)]);
405 ("fn", kw_name, false)
406 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
408 ("fn", kw_name, false)
409 } else if self.check(&token::Colon) {
413 ("fn` or `struct", "function or struct", true)
416 let msg = format!("missing `{kw}` for {kw_name} definition");
417 let mut err = self.struct_span_err(sp, &msg);
419 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
421 format!("add `{kw}` here to parse `{ident}` as a public {kw_name}");
422 err.span_suggestion_short(
426 Applicability::MachineApplicable,
428 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
431 "if you meant to call a macro, try",
432 format!("{}!", snippet),
433 // this is the `ambiguous` conditional branch
434 Applicability::MaybeIncorrect,
438 "if you meant to call a macro, remove the `pub` \
439 and add a trailing `!` after the identifier",
443 } else if self.look_ahead(1, |t| *t == token::Lt) {
444 let ident = self.parse_ident().unwrap();
445 self.eat_to_tokens(&[&token::Gt]);
447 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(Delimiter::Parenthesis)) {
448 ("fn", self.recover_first_param(), false)
449 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
450 ("struct", "struct", false)
452 ("fn` or `struct", "function or struct", true)
454 let msg = format!("missing `{kw}` for {kw_name} definition");
455 let mut err = self.struct_span_err(sp, &msg);
457 err.span_suggestion_short(
459 &format!("add `{kw}` here to parse `{ident}` as a public {kw_name}"),
461 Applicability::MachineApplicable,
470 /// Parses an item macro, e.g., `item!();`.
471 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
472 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
473 self.expect(&token::Not)?; // `!`
474 match self.parse_delim_args() {
475 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
477 self.eat_semi_for_macro_if_needed(&args);
478 self.complain_if_pub_macro(vis, false);
479 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
483 // Maybe the user misspelled `macro_rules` (issue #91227)
484 if self.token.is_ident()
485 && path.segments.len() == 1
486 && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
490 "perhaps you meant to define a macro",
492 Applicability::MachineApplicable,
500 /// Recover if we parsed attributes and expected an item but there was none.
501 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
502 let ([start @ end] | [start, .., end]) = attrs else {
505 let msg = if end.is_doc_comment() {
506 "expected item after doc comment"
508 "expected item after attributes"
510 let mut err = self.struct_span_err(end.span, msg);
511 if end.is_doc_comment() {
512 err.span_label(end.span, "this doc comment doesn't document anything");
514 if end.meta_kind().is_some() {
515 if self.token.kind == TokenKind::Semi {
516 err.span_suggestion_verbose(
518 "consider removing this semicolon",
520 Applicability::MaybeIncorrect,
524 if let [.., penultimate, _] = attrs {
525 err.span_label(start.span.to(penultimate.span), "other attributes here");
530 fn is_async_fn(&self) -> bool {
531 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
534 fn parse_polarity(&mut self) -> ast::ImplPolarity {
535 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
536 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
538 ast::ImplPolarity::Negative(self.prev_token.span)
540 ast::ImplPolarity::Positive
544 /// Parses an implementation item.
546 /// ```ignore (illustrative)
547 /// impl<'a, T> TYPE { /* impl items */ }
548 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
549 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
550 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
553 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
555 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
556 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
561 defaultness: Defaultness,
562 ) -> PResult<'a, ItemInfo> {
563 let unsafety = self.parse_unsafety(Case::Sensitive);
564 self.expect_keyword(kw::Impl)?;
566 // First, parse generic parameters if necessary.
567 let mut generics = if self.choose_generics_over_qpath(0) {
568 self.parse_generics()?
570 let mut generics = Generics::default();
572 // /\ this is where `generics.span` should point when there are no type params.
573 generics.span = self.prev_token.span.shrink_to_hi();
577 let constness = self.parse_constness(Case::Sensitive);
578 if let Const::Yes(span) = constness {
579 self.sess.gated_spans.gate(sym::const_trait_impl, span);
582 let polarity = self.parse_polarity();
584 // Parse both types and traits as a type, then reinterpret if necessary.
585 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
586 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
588 let span = self.prev_token.span.between(self.token.span);
589 self.struct_span_err(span, "missing trait in a trait impl")
594 Applicability::HasPlaceholders,
597 span.to(self.token.span),
598 "for an inherent impl, drop this `for`",
600 Applicability::MaybeIncorrect,
604 kind: TyKind::Path(None, err_path(span)),
610 self.parse_ty_with_generics_recovery(&generics)?
613 // If `for` is missing we try to recover.
614 let has_for = self.eat_keyword(kw::For);
615 let missing_for_span = self.prev_token.span.between(self.token.span);
617 let ty_second = if self.token == token::DotDot {
618 // We need to report this error after `cfg` expansion for compatibility reasons
619 self.bump(); // `..`, do not add it to expected tokens
620 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
621 } else if has_for || self.token.can_begin_type() {
622 Some(self.parse_ty()?)
627 generics.where_clause = self.parse_where_clause()?;
629 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
631 let item_kind = match ty_second {
633 // impl Trait for Type
635 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
636 .span_suggestion_short(
640 Applicability::MachineApplicable,
645 let ty_first = ty_first.into_inner();
646 let path = match ty_first.kind {
647 // This notably includes paths passed through `ty` macro fragments (#46438).
648 TyKind::Path(None, path) => path,
650 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
651 err_path(ty_first.span)
654 let trait_ref = TraitRef { path, ref_id: ty_first.id };
656 ItemKind::Impl(Box::new(Impl {
662 of_trait: Some(trait_ref),
669 ItemKind::Impl(Box::new(Impl {
682 Ok((Ident::empty(), item_kind))
685 fn parse_item_list<T>(
688 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
689 ) -> PResult<'a, Vec<T>> {
690 let open_brace_span = self.token.span;
692 // Recover `impl Ty;` instead of `impl Ty {}`
693 if self.token == TokenKind::Semi {
694 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
699 self.expect(&token::OpenDelim(Delimiter::Brace))?;
700 attrs.extend(self.parse_inner_attributes()?);
702 let mut items = Vec::new();
703 while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
704 if self.recover_doc_comment_before_brace() {
707 match parse_item(self) {
709 let is_unnecessary_semicolon = !items.is_empty()
710 // When the close delim is `)` in a case like the following, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
711 // but the actual `token.kind` is `token::CloseDelim(Delimiter::Bracket)`.
712 // This is because the `token.kind` of the close delim is treated as the same as
713 // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
714 // Therefore, `token.kind` should not be compared here.
719 // fn qux() -> Option<usize> {
722 // ^ this close delim
727 .span_to_snippet(self.prev_token.span)
728 .map_or(false, |snippet| snippet == "}")
729 && self.token.kind == token::Semi;
730 let semicolon_span = self.token.span;
731 // We have to bail or we'll potentially never make progress.
732 let non_item_span = self.token.span;
733 let is_let = self.token.is_keyword(kw::Let);
735 let mut err = self.struct_span_err(non_item_span, "non-item in item list");
736 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
740 "consider using `const` instead of `let` for associated const",
742 Applicability::MachineApplicable,
745 err.span_label(open_brace_span, "item list starts here")
746 .span_label(non_item_span, "non-item starts here")
747 .span_label(self.prev_token.span, "item list ends here");
749 if is_unnecessary_semicolon {
752 "consider removing this semicolon",
754 Applicability::MaybeIncorrect,
760 Ok(Some(item)) => items.extend(item),
762 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
763 err.span_label(open_brace_span, "while parsing this item list starting here")
764 .span_label(self.prev_token.span, "the item list ends here")
773 /// Recover on a doc comment before `}`.
774 fn recover_doc_comment_before_brace(&mut self) -> bool {
775 if let token::DocComment(..) = self.token.kind {
776 if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
781 "found a documentation comment that doesn't document anything",
783 .span_label(self.token.span, "this doc comment doesn't document anything")
785 "doc comments must come before what they document, if a comment was \
796 /// Parses defaultness (i.e., `default` or nothing).
797 fn parse_defaultness(&mut self) -> Defaultness {
798 // We are interested in `default` followed by another identifier.
799 // However, we must avoid keywords that occur as binary operators.
800 // Currently, the only applicable keyword is `as` (`default as Ty`).
801 if self.check_keyword(kw::Default)
802 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
804 self.bump(); // `default`
805 Defaultness::Default(self.prev_token.uninterpolated_span())
811 /// Is this an `(unsafe auto? | auto) trait` item?
812 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
814 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
816 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
819 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
820 fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
821 let unsafety = self.parse_unsafety(Case::Sensitive);
822 // Parse optional `auto` prefix.
823 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
825 self.expect_keyword(kw::Trait)?;
826 let ident = self.parse_ident()?;
827 let mut generics = self.parse_generics()?;
829 // Parse optional colon and supertrait bounds.
830 let had_colon = self.eat(&token::Colon);
831 let span_at_colon = self.prev_token.span;
832 let bounds = if had_colon {
833 self.parse_generic_bounds(Some(self.prev_token.span))?
838 let span_before_eq = self.prev_token.span;
839 if self.eat(&token::Eq) {
840 // It's a trait alias.
842 let span = span_at_colon.to(span_before_eq);
843 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
846 let bounds = self.parse_generic_bounds(None)?;
847 generics.where_clause = self.parse_where_clause()?;
850 let whole_span = lo.to(self.prev_token.span);
851 if is_auto == IsAuto::Yes {
852 let msg = "trait aliases cannot be `auto`";
853 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
855 if let Unsafe::Yes(_) = unsafety {
856 let msg = "trait aliases cannot be `unsafe`";
857 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
860 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
862 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
864 // It's a normal trait.
865 generics.where_clause = self.parse_where_clause()?;
866 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
869 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
874 pub fn parse_impl_item(
876 force_collect: ForceCollect,
877 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
878 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
879 self.parse_assoc_item(fn_parse_mode, force_collect)
882 pub fn parse_trait_item(
884 force_collect: ForceCollect,
885 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
887 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
888 self.parse_assoc_item(fn_parse_mode, force_collect)
891 /// Parses associated items.
894 fn_parse_mode: FnParseMode,
895 force_collect: ForceCollect,
896 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
897 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
898 |Item { attrs, id, span, vis, ident, kind, tokens }| {
899 let kind = match AssocItemKind::try_from(kind) {
901 Err(kind) => match kind {
902 ItemKind::Static(a, _, b) => {
903 self.struct_span_err(span, "associated `static` items are not allowed")
905 AssocItemKind::Const(Defaultness::Final, a, b)
907 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
910 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
915 /// Parses a `type` alias with the following grammar:
917 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
919 /// The `"type"` has already been eaten.
920 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
921 let ident = self.parse_ident()?;
922 let mut generics = self.parse_generics()?;
924 // Parse optional colon and param bounds.
926 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
927 let before_where_clause = self.parse_where_clause()?;
929 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
931 let after_where_clause = self.parse_where_clause()?;
933 let where_clauses = (
934 TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
935 TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
937 let where_predicates_split = before_where_clause.predicates.len();
938 let mut predicates = before_where_clause.predicates;
939 predicates.extend(after_where_clause.predicates.into_iter());
940 let where_clause = WhereClause {
941 has_where_token: before_where_clause.has_where_token
942 || after_where_clause.has_where_token,
946 generics.where_clause = where_clause;
952 ItemKind::TyAlias(Box::new(TyAlias {
956 where_predicates_split,
963 /// Parses a `UseTree`.
966 /// USE_TREE = [`::`] `*` |
967 /// [`::`] `{` USE_TREE_LIST `}` |
969 /// PATH `::` `{` USE_TREE_LIST `}` |
970 /// PATH [`as` IDENT]
972 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
973 let lo = self.token.span;
976 ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo(), tokens: None };
977 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
978 || self.check(&token::BinOp(token::Star))
979 || self.is_import_coupler()
981 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
982 let mod_sep_ctxt = self.token.span.ctxt();
983 if self.eat(&token::ModSep) {
986 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
989 self.parse_use_tree_glob_or_nested()?
991 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
992 prefix = self.parse_path(PathStyle::Mod)?;
994 if self.eat(&token::ModSep) {
995 self.parse_use_tree_glob_or_nested()?
997 // Recover from using a colon as path separator.
998 while self.eat_noexpect(&token::Colon) {
999 self.struct_span_err(self.prev_token.span, "expected `::`, found `:`")
1000 .span_suggestion_short(
1001 self.prev_token.span,
1004 Applicability::MachineApplicable,
1006 .note_once("import paths are delimited using `::`")
1009 // We parse the rest of the path and append it to the original prefix.
1010 self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1011 prefix.span = lo.to(self.prev_token.span);
1014 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
1018 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
1021 /// Parses `*` or `{...}`.
1022 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1023 Ok(if self.eat(&token::BinOp(token::Star)) {
1026 UseTreeKind::Nested(self.parse_use_tree_list()?)
1030 /// Parses a `UseTreeKind::Nested(list)`.
1033 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
1035 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1036 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
1040 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1041 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1044 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1045 match self.token.ident() {
1046 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1050 _ => self.parse_ident(),
1054 /// Parses `extern crate` links.
1058 /// ```ignore (illustrative)
1059 /// extern crate foo;
1060 /// extern crate bar as foo;
1062 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1063 // Accept `extern crate name-like-this` for better diagnostics
1064 let orig_name = self.parse_crate_name_with_dashes()?;
1065 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1066 (rename, Some(orig_name.name))
1070 self.expect_semi()?;
1071 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1074 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1075 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1076 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1078 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1079 self.parse_path_segment_ident()
1083 let mut idents = vec![];
1084 let mut replacement = vec![];
1085 let mut fixed_crate_name = false;
1086 // Accept `extern crate name-like-this` for better diagnostics.
1087 let dash = token::BinOp(token::BinOpToken::Minus);
1088 if self.token == dash {
1089 // Do not include `-` as part of the expected tokens list.
1090 while self.eat(&dash) {
1091 fixed_crate_name = true;
1092 replacement.push((self.prev_token.span, "_".to_string()));
1093 idents.push(self.parse_ident()?);
1096 if fixed_crate_name {
1097 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1098 let mut fixed_name = ident.name.to_string();
1099 for part in idents {
1100 fixed_name.push_str(&format!("_{}", part.name));
1102 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1104 self.struct_span_err(fixed_name_sp, error_msg)
1105 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1106 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1112 /// Parses `extern` for foreign ABIs modules.
1114 /// `extern` is expected to have been consumed before calling this method.
1118 /// ```ignore (only-for-syntax-highlight)
1122 fn parse_item_foreign_mod(
1124 attrs: &mut AttrVec,
1125 mut unsafety: Unsafe,
1126 ) -> PResult<'a, ItemInfo> {
1127 let abi = self.parse_abi(); // ABI?
1128 if unsafety == Unsafe::No
1129 && self.token.is_keyword(kw::Unsafe)
1130 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1132 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1134 unsafety = Unsafe::Yes(self.token.span);
1135 self.eat_keyword(kw::Unsafe);
1137 let module = ast::ForeignMod {
1140 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1142 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1145 /// Parses a foreign item (one in an `extern { ... }` block).
1146 pub fn parse_foreign_item(
1148 force_collect: ForceCollect,
1149 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1150 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1151 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1152 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1153 let kind = match ForeignItemKind::try_from(kind) {
1155 Err(kind) => match kind {
1156 ItemKind::Const(_, a, b) => {
1157 self.error_on_foreign_const(span, ident);
1158 ForeignItemKind::Static(a, Mutability::Not, b)
1160 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1163 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1168 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1169 let span = self.sess.source_map().guess_head_span(span);
1170 let descr = kind.descr();
1171 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1172 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1177 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1178 self.struct_span_err(ident.span, "extern items cannot be `const`")
1180 span.with_hi(ident.span.lo()),
1181 "try using a static value",
1183 Applicability::MachineApplicable,
1185 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1189 fn is_unsafe_foreign_mod(&self) -> bool {
1190 self.token.is_keyword(kw::Unsafe)
1191 && self.is_keyword_ahead(1, &[kw::Extern])
1193 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1194 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1198 fn is_static_global(&mut self) -> bool {
1199 if self.check_keyword(kw::Static) {
1200 // Check if this could be a closure.
1201 !self.look_ahead(1, |token| {
1202 if token.is_keyword(kw::Move) {
1205 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1212 /// Recover on `const mut` with `const` already eaten.
1213 fn recover_const_mut(&mut self, const_span: Span) {
1214 if self.eat_keyword(kw::Mut) {
1215 let span = self.prev_token.span;
1216 self.struct_span_err(span, "const globals cannot be mutable")
1217 .span_label(span, "cannot be mutable")
1220 "you might want to declare a static instead",
1222 Applicability::MaybeIncorrect,
1225 } else if self.eat_keyword(kw::Let) {
1226 let span = self.prev_token.span;
1227 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1229 const_span.to(span),
1232 Applicability::MaybeIncorrect,
1238 /// Recover on `const impl` with `const` already eaten.
1239 fn recover_const_impl(
1242 attrs: &mut AttrVec,
1243 defaultness: Defaultness,
1244 ) -> PResult<'a, ItemInfo> {
1245 let impl_span = self.token.span;
1246 let mut err = self.expected_ident_found();
1248 // Only try to recover if this is implementing a trait for a type
1249 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1250 Ok(impl_info) => impl_info,
1251 Err(recovery_error) => {
1252 // Recovery failed, raise the "expected identifier" error
1253 recovery_error.cancel();
1259 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1260 *constness = Const::Yes(const_span);
1262 let before_trait = trai.path.span.shrink_to_lo();
1263 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1264 err.multipart_suggestion(
1265 "you might have meant to write a const trait impl",
1266 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1267 Applicability::MaybeIncorrect,
1271 ItemKind::Impl { .. } => return Err(err),
1272 _ => unreachable!(),
1278 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1279 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1281 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1282 fn parse_item_global(
1284 m: Option<Mutability>,
1285 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1286 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1288 // Parse the type of a `const` or `static mut?` item.
1289 // That is, the `":" $ty` fragment.
1290 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1292 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1293 (true, false) => self.parse_ty()?,
1294 (colon, _) => self.recover_missing_const_type(colon, m),
1297 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1298 self.expect_semi()?;
1302 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1303 /// This means that the type is missing.
1304 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1305 // Construct the error and stash it away with the hope
1306 // that typeck will later enrich the error with a type.
1307 let kind = match m {
1308 Some(Mutability::Mut) => "static mut",
1309 Some(Mutability::Not) => "static",
1313 let colon = match colon_present {
1318 let span = self.prev_token.span.shrink_to_hi();
1319 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1320 err.span_suggestion(
1322 "provide a type for the item",
1323 format!("{colon} <type>"),
1324 Applicability::HasPlaceholders,
1326 err.stash(span, StashKey::ItemNoType);
1328 // The user intended that the type be inferred,
1329 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1330 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1333 /// Parses an enum declaration.
1334 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1335 if self.token.is_keyword(kw::Struct) {
1336 let span = self.prev_token.span.to(self.token.span);
1337 let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1338 err.span_suggestion(
1340 "replace `enum struct` with",
1342 Applicability::MachineApplicable,
1344 if self.look_ahead(1, |t| t.is_ident()) {
1352 let id = self.parse_ident()?;
1353 let mut generics = self.parse_generics()?;
1354 generics.where_clause = self.parse_where_clause()?;
1356 // Possibly recover `enum Foo;` instead of `enum Foo {}`
1357 let (variants, _) = if self.token == TokenKind::Semi {
1358 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1362 self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1364 e.span_label(id.span, "while parsing this enum");
1365 self.recover_stmt();
1371 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1372 Ok((id, ItemKind::Enum(enum_definition, generics)))
1375 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1376 let variant_attrs = self.parse_outer_attributes()?;
1377 self.collect_tokens_trailing_token(
1380 |this, variant_attrs| {
1381 let vlo = this.token.span;
1383 let vis = this.parse_visibility(FollowedByType::No)?;
1384 if !this.recover_nested_adt_item(kw::Enum)? {
1385 return Ok((None, TrailingToken::None));
1387 let ident = this.parse_field_ident("enum", vlo)?;
1389 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1390 // Parse a struct variant.
1391 let (fields, recovered) =
1392 this.parse_record_struct_body("struct", ident.span, false)?;
1393 VariantData::Struct(fields, recovered)
1394 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1395 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1397 VariantData::Unit(DUMMY_NODE_ID)
1401 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1403 let vr = ast::Variant {
1407 attrs: variant_attrs,
1410 span: vlo.to(this.prev_token.span),
1411 is_placeholder: false,
1414 Ok((Some(vr), TrailingToken::MaybeComma))
1419 /// Parses `struct Foo { ... }`.
1420 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1421 let class_name = self.parse_ident()?;
1423 let mut generics = self.parse_generics()?;
1425 // There is a special case worth noting here, as reported in issue #17904.
1426 // If we are parsing a tuple struct it is the case that the where clause
1427 // should follow the field list. Like so:
1429 // struct Foo<T>(T) where T: Copy;
1431 // If we are parsing a normal record-style struct it is the case
1432 // that the where clause comes before the body, and after the generics.
1433 // So if we look ahead and see a brace or a where-clause we begin
1434 // parsing a record style struct.
1436 // Otherwise if we look ahead and see a paren we parse a tuple-style
1439 let vdata = if self.token.is_keyword(kw::Where) {
1440 generics.where_clause = self.parse_where_clause()?;
1441 if self.eat(&token::Semi) {
1442 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1443 VariantData::Unit(DUMMY_NODE_ID)
1445 // If we see: `struct Foo<T> where T: Copy { ... }`
1446 let (fields, recovered) = self.parse_record_struct_body(
1449 generics.where_clause.has_where_token,
1451 VariantData::Struct(fields, recovered)
1453 // No `where` so: `struct Foo<T>;`
1454 } else if self.eat(&token::Semi) {
1455 VariantData::Unit(DUMMY_NODE_ID)
1456 // Record-style struct definition
1457 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1458 let (fields, recovered) = self.parse_record_struct_body(
1461 generics.where_clause.has_where_token,
1463 VariantData::Struct(fields, recovered)
1464 // Tuple-style struct definition with optional where-clause.
1465 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1466 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1467 generics.where_clause = self.parse_where_clause()?;
1468 self.expect_semi()?;
1471 let token_str = super::token_descr(&self.token);
1473 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1475 let mut err = self.struct_span_err(self.token.span, msg);
1476 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1480 Ok((class_name, ItemKind::Struct(vdata, generics)))
1483 /// Parses `union Foo { ... }`.
1484 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1485 let class_name = self.parse_ident()?;
1487 let mut generics = self.parse_generics()?;
1489 let vdata = if self.token.is_keyword(kw::Where) {
1490 generics.where_clause = self.parse_where_clause()?;
1491 let (fields, recovered) = self.parse_record_struct_body(
1494 generics.where_clause.has_where_token,
1496 VariantData::Struct(fields, recovered)
1497 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1498 let (fields, recovered) = self.parse_record_struct_body(
1501 generics.where_clause.has_where_token,
1503 VariantData::Struct(fields, recovered)
1505 let token_str = super::token_descr(&self.token);
1506 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1507 let mut err = self.struct_span_err(self.token.span, msg);
1508 err.span_label(self.token.span, "expected `where` or `{` after union name");
1512 Ok((class_name, ItemKind::Union(vdata, generics)))
1515 fn parse_record_struct_body(
1520 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1521 let mut fields = Vec::new();
1522 let mut recovered = false;
1523 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1524 while self.token != token::CloseDelim(Delimiter::Brace) {
1525 let field = self.parse_field_def(adt_ty).map_err(|e| {
1526 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1531 Ok(field) => fields.push(field),
1533 err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1539 self.eat(&token::CloseDelim(Delimiter::Brace));
1541 let token_str = super::token_descr(&self.token);
1543 "expected {}`{{` after struct name, found {}",
1544 if parsed_where { "" } else { "`where`, or " },
1547 let mut err = self.struct_span_err(self.token.span, msg);
1551 "expected {}`{{` after struct name",
1552 if parsed_where { "" } else { "`where`, or " }
1558 Ok((fields, recovered))
1561 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1562 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1563 // Unit like structs are handled in parse_item_struct function
1564 self.parse_paren_comma_seq(|p| {
1565 let attrs = p.parse_outer_attributes()?;
1566 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1567 let lo = p.token.span;
1568 let vis = p.parse_visibility(FollowedByType::Yes)?;
1569 let ty = p.parse_ty()?;
1573 span: lo.to(ty.span),
1579 is_placeholder: false,
1581 TrailingToken::MaybeComma,
1588 /// Parses an element of a struct declaration.
1589 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1590 let attrs = self.parse_outer_attributes()?;
1591 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1592 let lo = this.token.span;
1593 let vis = this.parse_visibility(FollowedByType::No)?;
1594 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1598 /// Parses a structure field declaration.
1599 fn parse_single_struct_field(
1605 ) -> PResult<'a, FieldDef> {
1606 let mut seen_comma: bool = false;
1607 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1608 if self.token == token::Comma {
1611 if self.eat(&token::Semi) {
1612 let sp = self.prev_token.span;
1613 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1614 err.span_suggestion_short(
1616 "replace `;` with `,`",
1618 Applicability::MachineApplicable,
1622 match self.token.kind {
1626 token::CloseDelim(Delimiter::Brace) => {}
1627 token::DocComment(..) => {
1628 let previous_span = self.prev_token.span;
1629 let mut err = DocCommentDoesNotDocumentAnything {
1630 span: self.token.span,
1631 missing_comma: None,
1633 self.bump(); // consume the doc comment
1634 let comma_after_doc_seen = self.eat(&token::Comma);
1635 // `seen_comma` is always false, because we are inside doc block
1636 // condition is here to make code more readable
1637 if !seen_comma && comma_after_doc_seen {
1640 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1641 self.sess.emit_err(err);
1644 let sp = previous_span.shrink_to_hi();
1645 err.missing_comma = Some(sp);
1647 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1651 let sp = self.prev_token.span.shrink_to_hi();
1652 let mut err = self.struct_span_err(
1654 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1657 // Try to recover extra trailing angle brackets
1658 let mut recovered = false;
1659 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1660 if let Some(last_segment) = segments.last() {
1661 recovered = self.check_trailing_angle_brackets(
1663 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1666 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1668 self.eat(&token::Comma);
1669 // `check_trailing_angle_brackets` already emitted a nicer error
1670 // NOTE(eddyb) this was `.cancel()`, but `err`
1671 // gets returned, so we can't fully defuse it.
1677 if self.token.is_ident()
1678 || (self.token.kind == TokenKind::Pound
1679 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1681 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1682 // emit the diagnostic and keep going
1683 err.span_suggestion(
1685 "try adding a comma",
1687 Applicability::MachineApplicable,
1694 // Make sure an error was emitted (either by recovering an angle bracket,
1695 // or by finding an identifier as the next token), since we're
1696 // going to continue parsing
1697 assert!(self.sess.span_diagnostic.has_errors().is_some());
1706 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1707 if let Err(mut err) = self.expect(&token::Colon) {
1708 let sm = self.sess.source_map();
1709 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1710 let semi_typo = self.token.kind == token::Semi
1711 && self.look_ahead(1, |t| {
1713 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1714 // when there's no type and `;` was used instead of a comma.
1715 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1716 (Ok(l), Ok(r)) => l.line == r.line,
1720 if eq_typo || semi_typo {
1722 // Gracefully handle small typos.
1723 err.span_suggestion_short(
1724 self.prev_token.span,
1725 "field names and their types are separated with `:`",
1727 Applicability::MachineApplicable,
1737 /// Parses a structure field.
1738 fn parse_name_and_ty(
1744 ) -> PResult<'a, FieldDef> {
1745 let name = self.parse_field_ident(adt_ty, lo)?;
1746 self.expect_field_ty_separator()?;
1747 let ty = self.parse_ty()?;
1748 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1749 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1750 .span_suggestion_verbose(
1752 "write a path separator here",
1754 Applicability::MaybeIncorrect,
1758 if self.token.kind == token::Eq {
1760 let const_expr = self.parse_anon_const_expr()?;
1761 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1762 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1765 "remove this unsupported default value",
1767 Applicability::MachineApplicable,
1772 span: lo.to(self.prev_token.span),
1778 is_placeholder: false,
1782 /// Parses a field identifier. Specialized version of `parse_ident_common`
1783 /// for better diagnostics and suggestions.
1784 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1785 let (ident, is_raw) = self.ident_or_err()?;
1786 if !is_raw && ident.is_reserved() {
1787 let snapshot = self.create_snapshot_for_diagnostic();
1788 let err = if self.check_fn_front_matter(false, Case::Sensitive) {
1789 let inherited_vis = Visibility {
1790 span: rustc_span::DUMMY_SP,
1791 kind: VisibilityKind::Inherited,
1794 // We use `parse_fn` to get a span for the function
1795 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1796 match self.parse_fn(&mut AttrVec::new(), fn_parse_mode, lo, &inherited_vis) {
1798 let mut err = self.struct_span_err(
1799 lo.to(self.prev_token.span),
1800 &format!("functions are not allowed in {adt_ty} definitions"),
1803 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1805 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1810 self.restore_snapshot(snapshot);
1811 self.expected_ident_found()
1814 } else if self.eat_keyword(kw::Struct) {
1815 match self.parse_item_struct() {
1817 let mut err = self.struct_span_err(
1818 lo.with_hi(ident.span.hi()),
1819 &format!("structs are not allowed in {adt_ty} definitions"),
1821 err.help("consider creating a new `struct` definition instead of nesting");
1826 self.restore_snapshot(snapshot);
1827 self.expected_ident_found()
1831 let mut err = self.expected_ident_found();
1832 if self.eat_keyword_noexpect(kw::Let)
1833 && let removal_span = self.prev_token.span.until(self.token.span)
1834 && let Ok(ident) = self.parse_ident_common(false)
1835 // Cancel this error, we don't need it.
1836 .map_err(|err| err.cancel())
1837 && self.token.kind == TokenKind::Colon
1839 err.span_suggestion(
1841 "remove this `let` keyword",
1843 Applicability::MachineApplicable,
1845 err.note("the `let` keyword is not allowed in `struct` fields");
1846 err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1850 self.restore_snapshot(snapshot);
1860 /// Parses a declarative macro 2.0 definition.
1861 /// The `macro` keyword has already been parsed.
1863 /// MacBody = "{" TOKEN_STREAM "}" ;
1864 /// MacParams = "(" TOKEN_STREAM ")" ;
1865 /// DeclMac = "macro" Ident MacParams? MacBody ;
1867 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1868 let ident = self.parse_ident()?;
1869 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1870 self.parse_delim_args()? // `MacBody`
1871 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1872 let params = self.parse_token_tree(); // `MacParams`
1873 let pspan = params.span();
1874 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1875 return self.unexpected();
1877 let body = self.parse_token_tree(); // `MacBody`
1878 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1879 let bspan = body.span();
1880 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1881 let tokens = TokenStream::new(vec![params, arrow, body]);
1882 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1883 P(DelimArgs { dspan, delim: MacDelimiter::Brace, tokens })
1885 return self.unexpected();
1888 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1889 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1892 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1893 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1894 if self.check_keyword(kw::MacroRules) {
1895 let macro_rules_span = self.token.span;
1897 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1898 return IsMacroRulesItem::Yes { has_bang: true };
1899 } else if self.look_ahead(1, |t| (t.is_ident())) {
1901 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1906 Applicability::MachineApplicable,
1910 return IsMacroRulesItem::Yes { has_bang: false };
1914 IsMacroRulesItem::No
1917 /// Parses a `macro_rules! foo { ... }` declarative macro.
1918 fn parse_item_macro_rules(
1922 ) -> PResult<'a, ItemInfo> {
1923 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1926 self.expect(&token::Not)?; // `!`
1928 let ident = self.parse_ident()?;
1930 if self.eat(&token::Not) {
1931 // Handle macro_rules! foo!
1932 let span = self.prev_token.span;
1933 self.struct_span_err(span, "macro names aren't followed by a `!`")
1934 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1938 let body = self.parse_delim_args()?;
1939 self.eat_semi_for_macro_if_needed(&body);
1940 self.complain_if_pub_macro(vis, true);
1942 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1945 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1946 /// If that's not the case, emit an error.
1947 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1948 if let VisibilityKind::Inherited = vis.kind {
1952 let vstr = pprust::vis_to_string(vis);
1953 let vstr = vstr.trim_end();
1955 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1956 self.struct_span_err(vis.span, &msg)
1959 "try exporting the macro",
1961 Applicability::MaybeIncorrect, // speculative
1965 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1968 "remove the visibility",
1970 Applicability::MachineApplicable,
1972 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1977 fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs) {
1978 if args.need_semicolon() && !self.eat(&token::Semi) {
1979 self.report_invalid_macro_expansion_item(args);
1983 fn report_invalid_macro_expansion_item(&self, args: &DelimArgs) {
1984 let span = args.dspan.entire();
1985 let mut err = self.struct_span_err(
1987 "macros that expand to items must be delimited with braces or followed by a semicolon",
1989 // FIXME: This will make us not emit the help even for declarative
1990 // macros within the same crate (that we can fix), which is sad.
1991 if !span.from_expansion() {
1992 if self.unclosed_delims.is_empty() {
1993 let DelimSpan { open, close } = args.dspan;
1994 err.multipart_suggestion(
1995 "change the delimiters to curly braces",
1996 vec![(open, "{".to_string()), (close, '}'.to_string())],
1997 Applicability::MaybeIncorrect,
2000 err.span_suggestion(
2002 "change the delimiters to curly braces",
2004 Applicability::HasPlaceholders,
2007 err.span_suggestion(
2008 span.shrink_to_hi(),
2011 Applicability::MaybeIncorrect,
2017 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2018 /// it is, we try to parse the item and report error about nested types.
2019 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2020 if (self.token.is_keyword(kw::Enum)
2021 || self.token.is_keyword(kw::Struct)
2022 || self.token.is_keyword(kw::Union))
2023 && self.look_ahead(1, |t| t.is_ident())
2025 let kw_token = self.token.clone();
2026 let kw_str = pprust::token_to_string(&kw_token);
2027 let item = self.parse_item(ForceCollect::No)?;
2029 self.struct_span_err(
2031 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
2035 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2037 Applicability::MaybeIncorrect,
2040 // We successfully parsed the item but we must inform the caller about nested problem.
2047 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2049 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2051 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2052 /// were allowed to omit parameter names. In 2018, they became required.
2053 type ReqName = fn(Edition) -> bool;
2055 /// Parsing configuration for functions.
2057 /// The syntax of function items is slightly different within trait definitions,
2058 /// impl blocks, and modules. It is still parsed using the same code, just with
2059 /// different flags set, so that even when the input is wrong and produces a parse
2060 /// error, it still gets into the AST and the rest of the parser and
2061 /// type checker can run.
2062 #[derive(Clone, Copy)]
2063 pub(crate) struct FnParseMode {
2064 /// A function pointer that decides if, per-parameter `p`, `p` must have a
2065 /// pattern or just a type. This field affects parsing of the parameters list.
2068 /// fn foo(alef: A) -> X { X::new() }
2069 /// -----^^ affects parsing this part of the function signature
2071 /// if req_name returns false, then this name is optional
2076 /// if req_name returns true, this is an error
2079 /// Calling this function pointer should only return false if:
2081 /// * The item is being parsed inside of a trait definition.
2082 /// Within an impl block or a module, it should always evaluate
2084 /// * The span is from Edition 2015. In particular, you can get a
2085 /// 2015 span inside a 2021 crate using macros.
2086 pub req_name: ReqName,
2087 /// If this flag is set to `true`, then plain, semicolon-terminated function
2088 /// prototypes are not allowed here.
2091 /// fn foo(alef: A) -> X { X::new() }
2094 /// this is always allowed
2096 /// fn bar(alef: A, bet: B) -> X;
2099 /// if req_body is set to true, this is an error
2102 /// This field should only be set to false if the item is inside of a trait
2103 /// definition or extern block. Within an impl block or a module, it should
2104 /// always be set to true.
2108 /// Parsing of functions and methods.
2109 impl<'a> Parser<'a> {
2110 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2113 attrs: &mut AttrVec,
2114 fn_parse_mode: FnParseMode,
2117 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2118 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
2119 let ident = self.parse_ident()?; // `foo`
2120 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2122 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
2123 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2125 let mut sig_hi = self.prev_token.span;
2126 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2127 let fn_sig_span = sig_lo.to(sig_hi);
2128 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2131 /// Parse the "body" of a function.
2132 /// This can either be `;` when there's no body,
2133 /// or e.g. a block when the function is a provided one.
2136 attrs: &mut AttrVec,
2140 ) -> PResult<'a, Option<P<Block>>> {
2141 let has_semi = if req_body {
2142 self.token.kind == TokenKind::Semi
2144 // Only include `;` in list of expected tokens if body is not required
2145 self.check(&TokenKind::Semi)
2147 let (inner_attrs, body) = if has_semi {
2148 // Include the trailing semicolon in the span of the signature
2149 self.expect_semi()?;
2150 *sig_hi = self.prev_token.span;
2151 (AttrVec::new(), None)
2152 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2153 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2154 } else if self.token.kind == token::Eq {
2155 // Recover `fn foo() = $expr;`.
2157 let eq_sp = self.prev_token.span;
2158 let _ = self.parse_expr()?;
2159 self.expect_semi()?; // `;`
2160 let span = eq_sp.to(self.prev_token.span);
2161 self.struct_span_err(span, "function body cannot be `= expression;`")
2162 .multipart_suggestion(
2163 "surround the expression with `{` and `}` instead of `=` and `;`",
2164 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2165 Applicability::MachineApplicable,
2168 (AttrVec::new(), Some(self.mk_block_err(span)))
2170 let expected = if req_body {
2171 &[token::OpenDelim(Delimiter::Brace)][..]
2173 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2175 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2176 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2177 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2178 // the AST for typechecking.
2179 err.span_label(ident.span, "while parsing this `fn`");
2185 (AttrVec::new(), None)
2187 attrs.extend(inner_attrs);
2191 /// Is the current token the start of an `FnHeader` / not a valid parse?
2193 /// `check_pub` adds additional `pub` to the checks in case users place it
2194 /// wrongly, can be used to ensure `pub` never comes after `default`.
2195 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2196 // We use an over-approximation here.
2197 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2198 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2199 // only if it wasn't preceded by `default` as `default pub` is invalid.
2200 let quals: &[Symbol] = if check_pub {
2201 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2203 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2205 self.check_keyword_case(kw::Fn, case) // Definitely an `fn`.
2206 // `$qual fn` or `$qual $qual`:
2207 || quals.iter().any(|&kw| self.check_keyword_case(kw, case))
2208 && self.look_ahead(1, |t| {
2209 // `$qual fn`, e.g. `const fn` or `async fn`.
2210 t.is_keyword_case(kw::Fn, case)
2211 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2214 t.is_non_raw_ident_where(|i|
2215 quals.contains(&i.name)
2216 // Rule out 2015 `const async: T = val`.
2219 || case == Case::Insensitive
2220 && t.is_non_raw_ident_where(|i| quals.iter().any(|qual| qual.as_str() == i.name.as_str().to_lowercase()))
2222 // Rule out unsafe extern block.
2223 && !self.is_unsafe_foreign_mod())
2226 || self.check_keyword_case(kw::Extern, case)
2227 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2228 && self.look_ahead(2, |t| t.is_keyword_case(kw::Fn, case))
2231 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2232 /// up to and including the `fn` keyword. The formal grammar is:
2235 /// Extern = "extern" StringLit? ;
2236 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2237 /// FnFrontMatter = FnQual "fn" ;
2240 /// `vis` represents the visibility that was already parsed, if any. Use
2241 /// `Visibility::Inherited` when no visibility is known.
2242 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2243 let sp_start = self.token.span;
2244 let constness = self.parse_constness(Case::Insensitive);
2246 let async_start_sp = self.token.span;
2247 let asyncness = self.parse_asyncness(Case::Insensitive);
2249 let unsafe_start_sp = self.token.span;
2250 let unsafety = self.parse_unsafety(Case::Insensitive);
2252 let ext_start_sp = self.token.span;
2253 let ext = self.parse_extern(Case::Insensitive);
2255 if let Async::Yes { span, .. } = asyncness {
2256 self.ban_async_in_2015(span);
2259 if !self.eat_keyword_case(kw::Fn, Case::Insensitive) {
2260 // It is possible for `expect_one_of` to recover given the contents of
2261 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2262 // account for this.
2263 match self.expect_one_of(&[], &[]) {
2265 Ok(false) => unreachable!(),
2267 // Qualifier keywords ordering check
2273 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2274 // that the keyword is already present and the second instance should be removed.
2275 let wrong_kw = if self.check_keyword(kw::Const) {
2277 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2278 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2280 } else if self.check_keyword(kw::Async) {
2282 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2283 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2285 } else if self.check_keyword(kw::Unsafe) {
2287 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2288 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2294 // The keyword is already present, suggest removal of the second instance
2295 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2296 let original_kw = self
2297 .span_to_snippet(original_sp)
2298 .expect("Span extracted directly from keyword should always work");
2300 err.span_suggestion(
2301 self.token.uninterpolated_span(),
2302 &format!("`{original_kw}` already used earlier, remove this one"),
2304 Applicability::MachineApplicable,
2306 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2308 // The keyword has not been seen yet, suggest correct placement in the function front matter
2309 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2310 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2311 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2312 let misplaced_qual_sp = self.token.uninterpolated_span();
2313 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2315 err.span_suggestion(
2316 correct_pos_sp.to(misplaced_qual_sp),
2317 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2318 format!("{misplaced_qual} {current_qual}"),
2319 Applicability::MachineApplicable,
2320 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2323 // Recover incorrect visibility order such as `async pub`
2324 else if self.check_keyword(kw::Pub) {
2325 let sp = sp_start.to(self.prev_token.span);
2326 if let Ok(snippet) = self.span_to_snippet(sp) {
2327 let current_vis = match self.parse_visibility(FollowedByType::No) {
2334 let vs = pprust::vis_to_string(¤t_vis);
2335 let vs = vs.trim_end();
2337 // There was no explicit visibility
2338 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2339 err.span_suggestion(
2340 sp_start.to(self.prev_token.span),
2341 &format!("visibility `{vs}` must come before `{snippet}`"),
2342 format!("{vs} {snippet}"),
2343 Applicability::MachineApplicable,
2346 // There was an explicit visibility
2348 err.span_suggestion(
2350 "there is already a visibility modifier, remove one",
2352 Applicability::MachineApplicable,
2354 .span_note(orig_vis.span, "explicit visibility first seen here");
2363 Ok(FnHeader { constness, unsafety, asyncness, ext })
2366 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2367 fn ban_async_in_2015(&self, span: Span) {
2368 if span.rust_2015() {
2369 let diag = self.diagnostic();
2370 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2371 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2372 .help_use_latest_edition()
2377 /// Parses the parameter list and result type of a function declaration.
2378 pub(super) fn parse_fn_decl(
2381 ret_allow_plus: AllowPlus,
2382 recover_return_sign: RecoverReturnSign,
2383 ) -> PResult<'a, P<FnDecl>> {
2385 inputs: self.parse_fn_params(req_name)?,
2386 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2390 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2391 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2392 let mut first_param = true;
2393 // Parse the arguments, starting out with `self` being allowed...
2394 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2395 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2397 let lo = p.prev_token.span;
2398 // Skip every token until next possible arg or end.
2399 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2400 // Create a placeholder argument for proper arg count (issue #34264).
2401 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2403 // ...now that we've parsed the first argument, `self` is no longer allowed.
2404 first_param = false;
2407 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2408 self.deduplicate_recovered_params_names(&mut params);
2412 /// Parses a single function parameter.
2414 /// - `self` is syntactically allowed when `first_param` holds.
2415 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2416 let lo = self.token.span;
2417 let attrs = self.parse_outer_attributes()?;
2418 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2419 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2420 if let Some(mut param) = this.parse_self_param()? {
2421 param.attrs = attrs;
2422 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2423 return Ok((res?, TrailingToken::None));
2426 let is_name_required = match this.token.kind {
2427 token::DotDotDot => false,
2428 _ => req_name(this.token.span.edition()),
2430 let (pat, ty) = if is_name_required || this.is_named_param() {
2431 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2433 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2435 let mut err = this.unexpected::<()>().unwrap_err();
2436 return if let Some(ident) =
2437 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2440 Ok((dummy_arg(ident), TrailingToken::None))
2446 this.eat_incorrect_doc_comment_for_param_type();
2447 (pat, this.parse_ty_for_param()?)
2449 debug!("parse_param_general ident_to_pat");
2450 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2451 this.eat_incorrect_doc_comment_for_param_type();
2452 let mut ty = this.parse_ty_for_param();
2454 && this.token != token::Comma
2455 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2457 // This wasn't actually a type, but a pattern looking like a type,
2458 // so we are going to rollback and re-parse for recovery.
2459 ty = this.unexpected();
2463 let ident = Ident::new(kw::Empty, this.prev_token.span);
2464 let bm = BindingAnnotation::NONE;
2465 let pat = this.mk_pat_ident(ty.span, bm, ident);
2468 // If this is a C-variadic argument and we hit an error, return the error.
2469 Err(err) if this.token == token::DotDotDot => return Err(err),
2470 // Recover from attempting to parse the argument as a type without pattern.
2473 this.restore_snapshot(parser_snapshot_before_ty);
2474 this.recover_arg_parse()?
2479 let span = lo.to(this.prev_token.span);
2482 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2483 TrailingToken::None,
2488 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2489 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2490 // Extract an identifier *after* having confirmed that the token is one.
2491 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2492 Some((ident, false)) => {
2496 _ => unreachable!(),
2498 // Is `self` `n` tokens ahead?
2499 let is_isolated_self = |this: &Self, n| {
2500 this.is_keyword_ahead(n, &[kw::SelfLower])
2501 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2503 // Is `mut self` `n` tokens ahead?
2504 let is_isolated_mut_self =
2505 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2506 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2507 let parse_self_possibly_typed = |this: &mut Self, m| {
2508 let eself_ident = expect_self_ident(this);
2509 let eself_hi = this.prev_token.span;
2510 let eself = if this.eat(&token::Colon) {
2511 SelfKind::Explicit(this.parse_ty()?, m)
2515 Ok((eself, eself_ident, eself_hi))
2517 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2518 let recover_self_ptr = |this: &mut Self| {
2519 let msg = "cannot pass `self` by raw pointer";
2520 let span = this.token.span;
2521 this.struct_span_err(span, msg).span_label(span, msg).emit();
2523 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2526 // Parse optional `self` parameter of a method.
2527 // Only a limited set of initial token sequences is considered `self` parameters; anything
2528 // else is parsed as a normal function parameter list, so some lookahead is required.
2529 let eself_lo = self.token.span;
2530 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2531 token::BinOp(token::And) => {
2532 let eself = if is_isolated_self(self, 1) {
2535 SelfKind::Region(None, Mutability::Not)
2536 } else if is_isolated_mut_self(self, 1) {
2540 SelfKind::Region(None, Mutability::Mut)
2541 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2544 let lt = self.expect_lifetime();
2545 SelfKind::Region(Some(lt), Mutability::Not)
2546 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2549 let lt = self.expect_lifetime();
2551 SelfKind::Region(Some(lt), Mutability::Mut)
2556 (eself, expect_self_ident(self), self.prev_token.span)
2559 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2561 recover_self_ptr(self)?
2563 // `*mut self` and `*const self`
2564 token::BinOp(token::Star)
2565 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2569 recover_self_ptr(self)?
2571 // `self` and `self: TYPE`
2572 token::Ident(..) if is_isolated_self(self, 0) => {
2573 parse_self_possibly_typed(self, Mutability::Not)?
2575 // `mut self` and `mut self: TYPE`
2576 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2578 parse_self_possibly_typed(self, Mutability::Mut)?
2580 _ => return Ok(None),
2583 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2584 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2587 fn is_named_param(&self) -> bool {
2588 let offset = match self.token.kind {
2589 token::Interpolated(ref nt) => match **nt {
2590 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2593 token::BinOp(token::And) | token::AndAnd => 1,
2594 _ if self.token.is_keyword(kw::Mut) => 1,
2598 self.look_ahead(offset, |t| t.is_ident())
2599 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2602 fn recover_first_param(&mut self) -> &'static str {
2604 .parse_outer_attributes()
2605 .and_then(|_| self.parse_self_param())
2606 .map_err(|e| e.cancel())
2608 Ok(Some(_)) => "method",
2614 enum IsMacroRulesItem {
2615 Yes { has_bang: bool },