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};
9 use rustc_ast::token::{self, Delimiter, TokenKind};
10 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
11 use rustc_ast::util::case::Case;
12 use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
13 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
14 use rustc_ast::{BindingAnnotation, Block, FnDecl, FnSig, Param, SelfKind};
15 use rustc_ast::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData};
16 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
17 use rustc_ast::{MacArgs, MacCall, MacDelimiter};
18 use rustc_ast_pretty::pprust;
19 use rustc_errors::{struct_span_err, Applicability, IntoDiagnostic, PResult, StashKey};
20 use rustc_span::edition::Edition;
21 use rustc_span::lev_distance::lev_distance;
22 use rustc_span::source_map::{self, Span};
23 use rustc_span::symbol::{kw, sym, Ident, Symbol};
24 use rustc_span::DUMMY_SP;
26 use std::convert::TryFrom;
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_mac_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;
975 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
976 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
977 || self.check(&token::BinOp(token::Star))
978 || self.is_import_coupler()
980 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
981 let mod_sep_ctxt = self.token.span.ctxt();
982 if self.eat(&token::ModSep) {
985 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
988 self.parse_use_tree_glob_or_nested()?
990 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
991 prefix = self.parse_path(PathStyle::Mod)?;
993 if self.eat(&token::ModSep) {
994 self.parse_use_tree_glob_or_nested()?
996 // Recover from using a colon as path separator.
997 while self.eat_noexpect(&token::Colon) {
998 self.struct_span_err(self.prev_token.span, "expected `::`, found `:`")
999 .span_suggestion_short(
1000 self.prev_token.span,
1003 Applicability::MachineApplicable,
1005 .note_once("import paths are delimited using `::`")
1008 // We parse the rest of the path and append it to the original prefix.
1009 self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1010 prefix.span = lo.to(self.prev_token.span);
1013 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
1017 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
1020 /// Parses `*` or `{...}`.
1021 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1022 Ok(if self.eat(&token::BinOp(token::Star)) {
1025 UseTreeKind::Nested(self.parse_use_tree_list()?)
1029 /// Parses a `UseTreeKind::Nested(list)`.
1032 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
1034 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1035 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
1039 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1040 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1043 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1044 match self.token.ident() {
1045 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1049 _ => self.parse_ident(),
1053 /// Parses `extern crate` links.
1057 /// ```ignore (illustrative)
1058 /// extern crate foo;
1059 /// extern crate bar as foo;
1061 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1062 // Accept `extern crate name-like-this` for better diagnostics
1063 let orig_name = self.parse_crate_name_with_dashes()?;
1064 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1065 (rename, Some(orig_name.name))
1069 self.expect_semi()?;
1070 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1073 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1074 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1075 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1077 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1078 self.parse_path_segment_ident()
1082 let mut idents = vec![];
1083 let mut replacement = vec![];
1084 let mut fixed_crate_name = false;
1085 // Accept `extern crate name-like-this` for better diagnostics.
1086 let dash = token::BinOp(token::BinOpToken::Minus);
1087 if self.token == dash {
1088 // Do not include `-` as part of the expected tokens list.
1089 while self.eat(&dash) {
1090 fixed_crate_name = true;
1091 replacement.push((self.prev_token.span, "_".to_string()));
1092 idents.push(self.parse_ident()?);
1095 if fixed_crate_name {
1096 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1097 let mut fixed_name = ident.name.to_string();
1098 for part in idents {
1099 fixed_name.push_str(&format!("_{}", part.name));
1101 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1103 self.struct_span_err(fixed_name_sp, error_msg)
1104 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1105 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1111 /// Parses `extern` for foreign ABIs modules.
1113 /// `extern` is expected to have been consumed before calling this method.
1117 /// ```ignore (only-for-syntax-highlight)
1121 fn parse_item_foreign_mod(
1123 attrs: &mut AttrVec,
1124 mut unsafety: Unsafe,
1125 ) -> PResult<'a, ItemInfo> {
1126 let abi = self.parse_abi(); // ABI?
1127 if unsafety == Unsafe::No
1128 && self.token.is_keyword(kw::Unsafe)
1129 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1131 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1133 unsafety = Unsafe::Yes(self.token.span);
1134 self.eat_keyword(kw::Unsafe);
1136 let module = ast::ForeignMod {
1139 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1141 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1144 /// Parses a foreign item (one in an `extern { ... }` block).
1145 pub fn parse_foreign_item(
1147 force_collect: ForceCollect,
1148 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1149 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1150 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1151 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1152 let kind = match ForeignItemKind::try_from(kind) {
1154 Err(kind) => match kind {
1155 ItemKind::Const(_, a, b) => {
1156 self.error_on_foreign_const(span, ident);
1157 ForeignItemKind::Static(a, Mutability::Not, b)
1159 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1162 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1167 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1168 let span = self.sess.source_map().guess_head_span(span);
1169 let descr = kind.descr();
1170 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1171 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1176 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1177 self.struct_span_err(ident.span, "extern items cannot be `const`")
1179 span.with_hi(ident.span.lo()),
1180 "try using a static value",
1182 Applicability::MachineApplicable,
1184 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1188 fn is_unsafe_foreign_mod(&self) -> bool {
1189 self.token.is_keyword(kw::Unsafe)
1190 && self.is_keyword_ahead(1, &[kw::Extern])
1192 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1193 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1197 fn is_static_global(&mut self) -> bool {
1198 if self.check_keyword(kw::Static) {
1199 // Check if this could be a closure.
1200 !self.look_ahead(1, |token| {
1201 if token.is_keyword(kw::Move) {
1204 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1211 /// Recover on `const mut` with `const` already eaten.
1212 fn recover_const_mut(&mut self, const_span: Span) {
1213 if self.eat_keyword(kw::Mut) {
1214 let span = self.prev_token.span;
1215 self.struct_span_err(span, "const globals cannot be mutable")
1216 .span_label(span, "cannot be mutable")
1219 "you might want to declare a static instead",
1221 Applicability::MaybeIncorrect,
1224 } else if self.eat_keyword(kw::Let) {
1225 let span = self.prev_token.span;
1226 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1228 const_span.to(span),
1231 Applicability::MaybeIncorrect,
1237 /// Recover on `const impl` with `const` already eaten.
1238 fn recover_const_impl(
1241 attrs: &mut AttrVec,
1242 defaultness: Defaultness,
1243 ) -> PResult<'a, ItemInfo> {
1244 let impl_span = self.token.span;
1245 let mut err = self.expected_ident_found();
1247 // Only try to recover if this is implementing a trait for a type
1248 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1249 Ok(impl_info) => impl_info,
1250 Err(recovery_error) => {
1251 // Recovery failed, raise the "expected identifier" error
1252 recovery_error.cancel();
1258 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1259 *constness = Const::Yes(const_span);
1261 let before_trait = trai.path.span.shrink_to_lo();
1262 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1263 err.multipart_suggestion(
1264 "you might have meant to write a const trait impl",
1265 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1266 Applicability::MaybeIncorrect,
1270 ItemKind::Impl { .. } => return Err(err),
1271 _ => unreachable!(),
1277 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1278 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1280 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1281 fn parse_item_global(
1283 m: Option<Mutability>,
1284 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1285 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1287 // Parse the type of a `const` or `static mut?` item.
1288 // That is, the `":" $ty` fragment.
1289 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1291 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1292 (true, false) => self.parse_ty()?,
1293 (colon, _) => self.recover_missing_const_type(colon, m),
1296 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1297 self.expect_semi()?;
1301 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1302 /// This means that the type is missing.
1303 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1304 // Construct the error and stash it away with the hope
1305 // that typeck will later enrich the error with a type.
1306 let kind = match m {
1307 Some(Mutability::Mut) => "static mut",
1308 Some(Mutability::Not) => "static",
1312 let colon = match colon_present {
1317 let span = self.prev_token.span.shrink_to_hi();
1318 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1319 err.span_suggestion(
1321 "provide a type for the item",
1322 format!("{colon} <type>"),
1323 Applicability::HasPlaceholders,
1325 err.stash(span, StashKey::ItemNoType);
1327 // The user intended that the type be inferred,
1328 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1329 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1332 /// Parses an enum declaration.
1333 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1334 if self.token.is_keyword(kw::Struct) {
1335 let span = self.prev_token.span.to(self.token.span);
1336 let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1337 err.span_suggestion(
1339 "replace `enum struct` with",
1341 Applicability::MachineApplicable,
1343 if self.look_ahead(1, |t| t.is_ident()) {
1351 let id = self.parse_ident()?;
1352 let mut generics = self.parse_generics()?;
1353 generics.where_clause = self.parse_where_clause()?;
1355 // Possibly recover `enum Foo;` instead of `enum Foo {}`
1356 let (variants, _) = if self.token == TokenKind::Semi {
1357 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1361 self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1363 e.span_label(id.span, "while parsing this enum");
1364 self.recover_stmt();
1370 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1371 Ok((id, ItemKind::Enum(enum_definition, generics)))
1374 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1375 let variant_attrs = self.parse_outer_attributes()?;
1376 self.collect_tokens_trailing_token(
1379 |this, variant_attrs| {
1380 let vlo = this.token.span;
1382 let vis = this.parse_visibility(FollowedByType::No)?;
1383 if !this.recover_nested_adt_item(kw::Enum)? {
1384 return Ok((None, TrailingToken::None));
1386 let ident = this.parse_field_ident("enum", vlo)?;
1388 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1389 // Parse a struct variant.
1390 let (fields, recovered) =
1391 this.parse_record_struct_body("struct", ident.span, false)?;
1392 VariantData::Struct(fields, recovered)
1393 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1394 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1396 VariantData::Unit(DUMMY_NODE_ID)
1400 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1402 let vr = ast::Variant {
1406 attrs: variant_attrs,
1409 span: vlo.to(this.prev_token.span),
1410 is_placeholder: false,
1413 Ok((Some(vr), TrailingToken::MaybeComma))
1418 /// Parses `struct Foo { ... }`.
1419 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1420 let class_name = self.parse_ident()?;
1422 let mut generics = self.parse_generics()?;
1424 // There is a special case worth noting here, as reported in issue #17904.
1425 // If we are parsing a tuple struct it is the case that the where clause
1426 // should follow the field list. Like so:
1428 // struct Foo<T>(T) where T: Copy;
1430 // If we are parsing a normal record-style struct it is the case
1431 // that the where clause comes before the body, and after the generics.
1432 // So if we look ahead and see a brace or a where-clause we begin
1433 // parsing a record style struct.
1435 // Otherwise if we look ahead and see a paren we parse a tuple-style
1438 let vdata = if self.token.is_keyword(kw::Where) {
1439 generics.where_clause = self.parse_where_clause()?;
1440 if self.eat(&token::Semi) {
1441 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1442 VariantData::Unit(DUMMY_NODE_ID)
1444 // If we see: `struct Foo<T> where T: Copy { ... }`
1445 let (fields, recovered) = self.parse_record_struct_body(
1448 generics.where_clause.has_where_token,
1450 VariantData::Struct(fields, recovered)
1452 // No `where` so: `struct Foo<T>;`
1453 } else if self.eat(&token::Semi) {
1454 VariantData::Unit(DUMMY_NODE_ID)
1455 // Record-style struct definition
1456 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1457 let (fields, recovered) = self.parse_record_struct_body(
1460 generics.where_clause.has_where_token,
1462 VariantData::Struct(fields, recovered)
1463 // Tuple-style struct definition with optional where-clause.
1464 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1465 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1466 generics.where_clause = self.parse_where_clause()?;
1467 self.expect_semi()?;
1470 let token_str = super::token_descr(&self.token);
1472 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1474 let mut err = self.struct_span_err(self.token.span, msg);
1475 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1479 Ok((class_name, ItemKind::Struct(vdata, generics)))
1482 /// Parses `union Foo { ... }`.
1483 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1484 let class_name = self.parse_ident()?;
1486 let mut generics = self.parse_generics()?;
1488 let vdata = if self.token.is_keyword(kw::Where) {
1489 generics.where_clause = self.parse_where_clause()?;
1490 let (fields, recovered) = self.parse_record_struct_body(
1493 generics.where_clause.has_where_token,
1495 VariantData::Struct(fields, recovered)
1496 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1497 let (fields, recovered) = self.parse_record_struct_body(
1500 generics.where_clause.has_where_token,
1502 VariantData::Struct(fields, recovered)
1504 let token_str = super::token_descr(&self.token);
1505 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1506 let mut err = self.struct_span_err(self.token.span, msg);
1507 err.span_label(self.token.span, "expected `where` or `{` after union name");
1511 Ok((class_name, ItemKind::Union(vdata, generics)))
1514 fn parse_record_struct_body(
1519 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1520 let mut fields = Vec::new();
1521 let mut recovered = false;
1522 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1523 while self.token != token::CloseDelim(Delimiter::Brace) {
1524 let field = self.parse_field_def(adt_ty).map_err(|e| {
1525 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1530 Ok(field) => fields.push(field),
1532 err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1538 self.eat(&token::CloseDelim(Delimiter::Brace));
1540 let token_str = super::token_descr(&self.token);
1542 "expected {}`{{` after struct name, found {}",
1543 if parsed_where { "" } else { "`where`, or " },
1546 let mut err = self.struct_span_err(self.token.span, msg);
1550 "expected {}`{{` after struct name",
1551 if parsed_where { "" } else { "`where`, or " }
1557 Ok((fields, recovered))
1560 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1561 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1562 // Unit like structs are handled in parse_item_struct function
1563 self.parse_paren_comma_seq(|p| {
1564 let attrs = p.parse_outer_attributes()?;
1565 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1566 let lo = p.token.span;
1567 let vis = p.parse_visibility(FollowedByType::Yes)?;
1568 let ty = p.parse_ty()?;
1572 span: lo.to(ty.span),
1578 is_placeholder: false,
1580 TrailingToken::MaybeComma,
1587 /// Parses an element of a struct declaration.
1588 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1589 let attrs = self.parse_outer_attributes()?;
1590 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1591 let lo = this.token.span;
1592 let vis = this.parse_visibility(FollowedByType::No)?;
1593 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1597 /// Parses a structure field declaration.
1598 fn parse_single_struct_field(
1604 ) -> PResult<'a, FieldDef> {
1605 let mut seen_comma: bool = false;
1606 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1607 if self.token == token::Comma {
1610 if self.eat(&token::Semi) {
1611 let sp = self.prev_token.span;
1612 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1613 err.span_suggestion_short(
1615 "replace `;` with `,`",
1617 Applicability::MachineApplicable,
1621 match self.token.kind {
1625 token::CloseDelim(Delimiter::Brace) => {}
1626 token::DocComment(..) => {
1627 let previous_span = self.prev_token.span;
1628 let mut err = DocCommentDoesNotDocumentAnything {
1629 span: self.token.span,
1630 missing_comma: None,
1632 self.bump(); // consume the doc comment
1633 let comma_after_doc_seen = self.eat(&token::Comma);
1634 // `seen_comma` is always false, because we are inside doc block
1635 // condition is here to make code more readable
1636 if !seen_comma && comma_after_doc_seen {
1639 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1640 self.sess.emit_err(err);
1643 let sp = previous_span.shrink_to_hi();
1644 err.missing_comma = Some(sp);
1646 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1650 let sp = self.prev_token.span.shrink_to_hi();
1651 let mut err = self.struct_span_err(
1653 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1656 // Try to recover extra trailing angle brackets
1657 let mut recovered = false;
1658 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1659 if let Some(last_segment) = segments.last() {
1660 recovered = self.check_trailing_angle_brackets(
1662 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1665 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1667 self.eat(&token::Comma);
1668 // `check_trailing_angle_brackets` already emitted a nicer error
1669 // NOTE(eddyb) this was `.cancel()`, but `err`
1670 // gets returned, so we can't fully defuse it.
1676 if self.token.is_ident()
1677 || (self.token.kind == TokenKind::Pound
1678 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1680 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1681 // emit the diagnostic and keep going
1682 err.span_suggestion(
1684 "try adding a comma",
1686 Applicability::MachineApplicable,
1693 // Make sure an error was emitted (either by recovering an angle bracket,
1694 // or by finding an identifier as the next token), since we're
1695 // going to continue parsing
1696 assert!(self.sess.span_diagnostic.has_errors().is_some());
1705 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1706 if let Err(mut err) = self.expect(&token::Colon) {
1707 let sm = self.sess.source_map();
1708 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1709 let semi_typo = self.token.kind == token::Semi
1710 && self.look_ahead(1, |t| {
1712 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1713 // when there's no type and `;` was used instead of a comma.
1714 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1715 (Ok(l), Ok(r)) => l.line == r.line,
1719 if eq_typo || semi_typo {
1721 // Gracefully handle small typos.
1722 err.span_suggestion_short(
1723 self.prev_token.span,
1724 "field names and their types are separated with `:`",
1726 Applicability::MachineApplicable,
1736 /// Parses a structure field.
1737 fn parse_name_and_ty(
1743 ) -> PResult<'a, FieldDef> {
1744 let name = self.parse_field_ident(adt_ty, lo)?;
1745 self.expect_field_ty_separator()?;
1746 let ty = self.parse_ty()?;
1747 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1748 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1749 .span_suggestion_verbose(
1751 "write a path separator here",
1753 Applicability::MaybeIncorrect,
1757 if self.token.kind == token::Eq {
1759 let const_expr = self.parse_anon_const_expr()?;
1760 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1761 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1764 "remove this unsupported default value",
1766 Applicability::MachineApplicable,
1771 span: lo.to(self.prev_token.span),
1777 is_placeholder: false,
1781 /// Parses a field identifier. Specialized version of `parse_ident_common`
1782 /// for better diagnostics and suggestions.
1783 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1784 let (ident, is_raw) = self.ident_or_err()?;
1785 if !is_raw && ident.is_reserved() {
1786 let snapshot = self.create_snapshot_for_diagnostic();
1787 let err = if self.check_fn_front_matter(false, Case::Sensitive) {
1788 let inherited_vis = Visibility {
1789 span: rustc_span::DUMMY_SP,
1790 kind: VisibilityKind::Inherited,
1793 // We use `parse_fn` to get a span for the function
1794 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1795 match self.parse_fn(&mut AttrVec::new(), fn_parse_mode, lo, &inherited_vis) {
1797 let mut err = self.struct_span_err(
1798 lo.to(self.prev_token.span),
1799 &format!("functions are not allowed in {adt_ty} definitions"),
1802 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1804 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1809 self.restore_snapshot(snapshot);
1810 self.expected_ident_found()
1813 } else if self.eat_keyword(kw::Struct) {
1814 match self.parse_item_struct() {
1816 let mut err = self.struct_span_err(
1817 lo.with_hi(ident.span.hi()),
1818 &format!("structs are not allowed in {adt_ty} definitions"),
1820 err.help("consider creating a new `struct` definition instead of nesting");
1825 self.restore_snapshot(snapshot);
1826 self.expected_ident_found()
1830 let mut err = self.expected_ident_found();
1831 if self.eat_keyword_noexpect(kw::Let)
1832 && let removal_span = self.prev_token.span.until(self.token.span)
1833 && let Ok(ident) = self.parse_ident_common(false)
1834 // Cancel this error, we don't need it.
1835 .map_err(|err| err.cancel())
1836 && self.token.kind == TokenKind::Colon
1838 err.span_suggestion(
1840 "remove this `let` keyword",
1842 Applicability::MachineApplicable,
1844 err.note("the `let` keyword is not allowed in `struct` fields");
1845 err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1849 self.restore_snapshot(snapshot);
1859 /// Parses a declarative macro 2.0 definition.
1860 /// The `macro` keyword has already been parsed.
1862 /// MacBody = "{" TOKEN_STREAM "}" ;
1863 /// MacParams = "(" TOKEN_STREAM ")" ;
1864 /// DeclMac = "macro" Ident MacParams? MacBody ;
1866 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1867 let ident = self.parse_ident()?;
1868 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1869 self.parse_mac_args()? // `MacBody`
1870 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1871 let params = self.parse_token_tree(); // `MacParams`
1872 let pspan = params.span();
1873 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1874 return self.unexpected();
1876 let body = self.parse_token_tree(); // `MacBody`
1877 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1878 let bspan = body.span();
1879 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1880 let tokens = TokenStream::new(vec![params, arrow, body]);
1881 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1882 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1884 return self.unexpected();
1887 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1888 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1891 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1892 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1893 if self.check_keyword(kw::MacroRules) {
1894 let macro_rules_span = self.token.span;
1896 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1897 return IsMacroRulesItem::Yes { has_bang: true };
1898 } else if self.look_ahead(1, |t| (t.is_ident())) {
1900 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1905 Applicability::MachineApplicable,
1909 return IsMacroRulesItem::Yes { has_bang: false };
1913 IsMacroRulesItem::No
1916 /// Parses a `macro_rules! foo { ... }` declarative macro.
1917 fn parse_item_macro_rules(
1921 ) -> PResult<'a, ItemInfo> {
1922 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1925 self.expect(&token::Not)?; // `!`
1927 let ident = self.parse_ident()?;
1929 if self.eat(&token::Not) {
1930 // Handle macro_rules! foo!
1931 let span = self.prev_token.span;
1932 self.struct_span_err(span, "macro names aren't followed by a `!`")
1933 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1937 let body = self.parse_mac_args()?;
1938 self.eat_semi_for_macro_if_needed(&body);
1939 self.complain_if_pub_macro(vis, true);
1941 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1944 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1945 /// If that's not the case, emit an error.
1946 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1947 if let VisibilityKind::Inherited = vis.kind {
1951 let vstr = pprust::vis_to_string(vis);
1952 let vstr = vstr.trim_end();
1954 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1955 self.struct_span_err(vis.span, &msg)
1958 "try exporting the macro",
1960 Applicability::MaybeIncorrect, // speculative
1964 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1967 "remove the visibility",
1969 Applicability::MachineApplicable,
1971 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1976 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1977 if args.need_semicolon() && !self.eat(&token::Semi) {
1978 self.report_invalid_macro_expansion_item(args);
1982 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1983 let span = args.span().expect("undelimited macro call");
1984 let mut err = self.struct_span_err(
1986 "macros that expand to items must be delimited with braces or followed by a semicolon",
1988 // FIXME: This will make us not emit the help even for declarative
1989 // macros within the same crate (that we can fix), which is sad.
1990 if !span.from_expansion() {
1991 if self.unclosed_delims.is_empty() {
1992 let DelimSpan { open, close } = match args {
1993 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1994 MacArgs::Delimited(dspan, ..) => *dspan,
1996 err.multipart_suggestion(
1997 "change the delimiters to curly braces",
1998 vec![(open, "{".to_string()), (close, '}'.to_string())],
1999 Applicability::MaybeIncorrect,
2002 err.span_suggestion(
2004 "change the delimiters to curly braces",
2006 Applicability::HasPlaceholders,
2009 err.span_suggestion(
2010 span.shrink_to_hi(),
2013 Applicability::MaybeIncorrect,
2019 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2020 /// it is, we try to parse the item and report error about nested types.
2021 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2022 if (self.token.is_keyword(kw::Enum)
2023 || self.token.is_keyword(kw::Struct)
2024 || self.token.is_keyword(kw::Union))
2025 && self.look_ahead(1, |t| t.is_ident())
2027 let kw_token = self.token.clone();
2028 let kw_str = pprust::token_to_string(&kw_token);
2029 let item = self.parse_item(ForceCollect::No)?;
2031 self.struct_span_err(
2033 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
2037 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2039 Applicability::MaybeIncorrect,
2042 // We successfully parsed the item but we must inform the caller about nested problem.
2049 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2051 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2053 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2054 /// were allowed to omit parameter names. In 2018, they became required.
2055 type ReqName = fn(Edition) -> bool;
2057 /// Parsing configuration for functions.
2059 /// The syntax of function items is slightly different within trait definitions,
2060 /// impl blocks, and modules. It is still parsed using the same code, just with
2061 /// different flags set, so that even when the input is wrong and produces a parse
2062 /// error, it still gets into the AST and the rest of the parser and
2063 /// type checker can run.
2064 #[derive(Clone, Copy)]
2065 pub(crate) struct FnParseMode {
2066 /// A function pointer that decides if, per-parameter `p`, `p` must have a
2067 /// pattern or just a type. This field affects parsing of the parameters list.
2070 /// fn foo(alef: A) -> X { X::new() }
2071 /// -----^^ affects parsing this part of the function signature
2073 /// if req_name returns false, then this name is optional
2078 /// if req_name returns true, this is an error
2081 /// Calling this function pointer should only return false if:
2083 /// * The item is being parsed inside of a trait definition.
2084 /// Within an impl block or a module, it should always evaluate
2086 /// * The span is from Edition 2015. In particular, you can get a
2087 /// 2015 span inside a 2021 crate using macros.
2088 pub req_name: ReqName,
2089 /// If this flag is set to `true`, then plain, semicolon-terminated function
2090 /// prototypes are not allowed here.
2093 /// fn foo(alef: A) -> X { X::new() }
2096 /// this is always allowed
2098 /// fn bar(alef: A, bet: B) -> X;
2101 /// if req_body is set to true, this is an error
2104 /// This field should only be set to false if the item is inside of a trait
2105 /// definition or extern block. Within an impl block or a module, it should
2106 /// always be set to true.
2110 /// Parsing of functions and methods.
2111 impl<'a> Parser<'a> {
2112 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2115 attrs: &mut AttrVec,
2116 fn_parse_mode: FnParseMode,
2119 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2120 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
2121 let ident = self.parse_ident()?; // `foo`
2122 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2124 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
2125 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2127 let mut sig_hi = self.prev_token.span;
2128 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2129 let fn_sig_span = sig_lo.to(sig_hi);
2130 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2133 /// Parse the "body" of a function.
2134 /// This can either be `;` when there's no body,
2135 /// or e.g. a block when the function is a provided one.
2138 attrs: &mut AttrVec,
2142 ) -> PResult<'a, Option<P<Block>>> {
2143 let has_semi = if req_body {
2144 self.token.kind == TokenKind::Semi
2146 // Only include `;` in list of expected tokens if body is not required
2147 self.check(&TokenKind::Semi)
2149 let (inner_attrs, body) = if has_semi {
2150 // Include the trailing semicolon in the span of the signature
2151 self.expect_semi()?;
2152 *sig_hi = self.prev_token.span;
2153 (AttrVec::new(), None)
2154 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2155 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2156 } else if self.token.kind == token::Eq {
2157 // Recover `fn foo() = $expr;`.
2159 let eq_sp = self.prev_token.span;
2160 let _ = self.parse_expr()?;
2161 self.expect_semi()?; // `;`
2162 let span = eq_sp.to(self.prev_token.span);
2163 self.struct_span_err(span, "function body cannot be `= expression;`")
2164 .multipart_suggestion(
2165 "surround the expression with `{` and `}` instead of `=` and `;`",
2166 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2167 Applicability::MachineApplicable,
2170 (AttrVec::new(), Some(self.mk_block_err(span)))
2172 let expected = if req_body {
2173 &[token::OpenDelim(Delimiter::Brace)][..]
2175 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2177 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2178 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2179 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2180 // the AST for typechecking.
2181 err.span_label(ident.span, "while parsing this `fn`");
2187 (AttrVec::new(), None)
2189 attrs.extend(inner_attrs);
2193 /// Is the current token the start of an `FnHeader` / not a valid parse?
2195 /// `check_pub` adds additional `pub` to the checks in case users place it
2196 /// wrongly, can be used to ensure `pub` never comes after `default`.
2197 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2198 // We use an over-approximation here.
2199 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2200 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2201 // only if it wasn't preceded by `default` as `default pub` is invalid.
2202 let quals: &[Symbol] = if check_pub {
2203 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2205 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2207 self.check_keyword_case(kw::Fn, case) // Definitely an `fn`.
2208 // `$qual fn` or `$qual $qual`:
2209 || quals.iter().any(|&kw| self.check_keyword_case(kw, case))
2210 && self.look_ahead(1, |t| {
2211 // `$qual fn`, e.g. `const fn` or `async fn`.
2212 t.is_keyword_case(kw::Fn, case)
2213 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2216 t.is_non_raw_ident_where(|i|
2217 quals.contains(&i.name)
2218 // Rule out 2015 `const async: T = val`.
2221 || case == Case::Insensitive
2222 && t.is_non_raw_ident_where(|i| quals.iter().any(|qual| qual.as_str() == i.name.as_str().to_lowercase()))
2224 // Rule out unsafe extern block.
2225 && !self.is_unsafe_foreign_mod())
2228 || self.check_keyword_case(kw::Extern, case)
2229 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2230 && self.look_ahead(2, |t| t.is_keyword_case(kw::Fn, case))
2233 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2234 /// up to and including the `fn` keyword. The formal grammar is:
2237 /// Extern = "extern" StringLit? ;
2238 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2239 /// FnFrontMatter = FnQual "fn" ;
2242 /// `vis` represents the visibility that was already parsed, if any. Use
2243 /// `Visibility::Inherited` when no visibility is known.
2244 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2245 let sp_start = self.token.span;
2246 let constness = self.parse_constness(Case::Insensitive);
2248 let async_start_sp = self.token.span;
2249 let asyncness = self.parse_asyncness(Case::Insensitive);
2251 let unsafe_start_sp = self.token.span;
2252 let unsafety = self.parse_unsafety(Case::Insensitive);
2254 let ext_start_sp = self.token.span;
2255 let ext = self.parse_extern(Case::Insensitive);
2257 if let Async::Yes { span, .. } = asyncness {
2258 self.ban_async_in_2015(span);
2261 if !self.eat_keyword_case(kw::Fn, Case::Insensitive) {
2262 // It is possible for `expect_one_of` to recover given the contents of
2263 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2264 // account for this.
2265 match self.expect_one_of(&[], &[]) {
2267 Ok(false) => unreachable!(),
2269 // Qualifier keywords ordering check
2275 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2276 // that the keyword is already present and the second instance should be removed.
2277 let wrong_kw = if self.check_keyword(kw::Const) {
2279 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2280 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2282 } else if self.check_keyword(kw::Async) {
2284 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2285 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2287 } else if self.check_keyword(kw::Unsafe) {
2289 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2290 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2296 // The keyword is already present, suggest removal of the second instance
2297 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2298 let original_kw = self
2299 .span_to_snippet(original_sp)
2300 .expect("Span extracted directly from keyword should always work");
2302 err.span_suggestion(
2303 self.token.uninterpolated_span(),
2304 &format!("`{original_kw}` already used earlier, remove this one"),
2306 Applicability::MachineApplicable,
2308 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2310 // The keyword has not been seen yet, suggest correct placement in the function front matter
2311 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2312 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2313 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2314 let misplaced_qual_sp = self.token.uninterpolated_span();
2315 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2317 err.span_suggestion(
2318 correct_pos_sp.to(misplaced_qual_sp),
2319 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2320 format!("{misplaced_qual} {current_qual}"),
2321 Applicability::MachineApplicable,
2322 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2325 // Recover incorrect visibility order such as `async pub`
2326 else if self.check_keyword(kw::Pub) {
2327 let sp = sp_start.to(self.prev_token.span);
2328 if let Ok(snippet) = self.span_to_snippet(sp) {
2329 let current_vis = match self.parse_visibility(FollowedByType::No) {
2336 let vs = pprust::vis_to_string(¤t_vis);
2337 let vs = vs.trim_end();
2339 // There was no explicit visibility
2340 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2341 err.span_suggestion(
2342 sp_start.to(self.prev_token.span),
2343 &format!("visibility `{vs}` must come before `{snippet}`"),
2344 format!("{vs} {snippet}"),
2345 Applicability::MachineApplicable,
2348 // There was an explicit visibility
2350 err.span_suggestion(
2352 "there is already a visibility modifier, remove one",
2354 Applicability::MachineApplicable,
2356 .span_note(orig_vis.span, "explicit visibility first seen here");
2365 Ok(FnHeader { constness, unsafety, asyncness, ext })
2368 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2369 fn ban_async_in_2015(&self, span: Span) {
2370 if span.rust_2015() {
2371 let diag = self.diagnostic();
2372 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2373 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2374 .help_use_latest_edition()
2379 /// Parses the parameter list and result type of a function declaration.
2380 pub(super) fn parse_fn_decl(
2383 ret_allow_plus: AllowPlus,
2384 recover_return_sign: RecoverReturnSign,
2385 ) -> PResult<'a, P<FnDecl>> {
2387 inputs: self.parse_fn_params(req_name)?,
2388 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2392 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2393 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2394 let mut first_param = true;
2395 // Parse the arguments, starting out with `self` being allowed...
2396 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2397 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2399 let lo = p.prev_token.span;
2400 // Skip every token until next possible arg or end.
2401 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2402 // Create a placeholder argument for proper arg count (issue #34264).
2403 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2405 // ...now that we've parsed the first argument, `self` is no longer allowed.
2406 first_param = false;
2409 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2410 self.deduplicate_recovered_params_names(&mut params);
2414 /// Parses a single function parameter.
2416 /// - `self` is syntactically allowed when `first_param` holds.
2417 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2418 let lo = self.token.span;
2419 let attrs = self.parse_outer_attributes()?;
2420 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2421 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2422 if let Some(mut param) = this.parse_self_param()? {
2423 param.attrs = attrs;
2424 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2425 return Ok((res?, TrailingToken::None));
2428 let is_name_required = match this.token.kind {
2429 token::DotDotDot => false,
2430 _ => req_name(this.token.span.edition()),
2432 let (pat, ty) = if is_name_required || this.is_named_param() {
2433 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2435 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2437 let mut err = this.unexpected::<()>().unwrap_err();
2438 return if let Some(ident) =
2439 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2442 Ok((dummy_arg(ident), TrailingToken::None))
2448 this.eat_incorrect_doc_comment_for_param_type();
2449 (pat, this.parse_ty_for_param()?)
2451 debug!("parse_param_general ident_to_pat");
2452 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2453 this.eat_incorrect_doc_comment_for_param_type();
2454 let mut ty = this.parse_ty_for_param();
2456 && this.token != token::Comma
2457 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2459 // This wasn't actually a type, but a pattern looking like a type,
2460 // so we are going to rollback and re-parse for recovery.
2461 ty = this.unexpected();
2465 let ident = Ident::new(kw::Empty, this.prev_token.span);
2466 let bm = BindingAnnotation::NONE;
2467 let pat = this.mk_pat_ident(ty.span, bm, ident);
2470 // If this is a C-variadic argument and we hit an error, return the error.
2471 Err(err) if this.token == token::DotDotDot => return Err(err),
2472 // Recover from attempting to parse the argument as a type without pattern.
2475 this.restore_snapshot(parser_snapshot_before_ty);
2476 this.recover_arg_parse()?
2481 let span = lo.to(this.prev_token.span);
2484 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2485 TrailingToken::None,
2490 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2491 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2492 // Extract an identifier *after* having confirmed that the token is one.
2493 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2494 Some((ident, false)) => {
2498 _ => unreachable!(),
2500 // Is `self` `n` tokens ahead?
2501 let is_isolated_self = |this: &Self, n| {
2502 this.is_keyword_ahead(n, &[kw::SelfLower])
2503 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2505 // Is `mut self` `n` tokens ahead?
2506 let is_isolated_mut_self =
2507 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2508 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2509 let parse_self_possibly_typed = |this: &mut Self, m| {
2510 let eself_ident = expect_self_ident(this);
2511 let eself_hi = this.prev_token.span;
2512 let eself = if this.eat(&token::Colon) {
2513 SelfKind::Explicit(this.parse_ty()?, m)
2517 Ok((eself, eself_ident, eself_hi))
2519 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2520 let recover_self_ptr = |this: &mut Self| {
2521 let msg = "cannot pass `self` by raw pointer";
2522 let span = this.token.span;
2523 this.struct_span_err(span, msg).span_label(span, msg).emit();
2525 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2528 // Parse optional `self` parameter of a method.
2529 // Only a limited set of initial token sequences is considered `self` parameters; anything
2530 // else is parsed as a normal function parameter list, so some lookahead is required.
2531 let eself_lo = self.token.span;
2532 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2533 token::BinOp(token::And) => {
2534 let eself = if is_isolated_self(self, 1) {
2537 SelfKind::Region(None, Mutability::Not)
2538 } else if is_isolated_mut_self(self, 1) {
2542 SelfKind::Region(None, Mutability::Mut)
2543 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2546 let lt = self.expect_lifetime();
2547 SelfKind::Region(Some(lt), Mutability::Not)
2548 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2551 let lt = self.expect_lifetime();
2553 SelfKind::Region(Some(lt), Mutability::Mut)
2558 (eself, expect_self_ident(self), self.prev_token.span)
2561 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2563 recover_self_ptr(self)?
2565 // `*mut self` and `*const self`
2566 token::BinOp(token::Star)
2567 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2571 recover_self_ptr(self)?
2573 // `self` and `self: TYPE`
2574 token::Ident(..) if is_isolated_self(self, 0) => {
2575 parse_self_possibly_typed(self, Mutability::Not)?
2577 // `mut self` and `mut self: TYPE`
2578 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2580 parse_self_possibly_typed(self, Mutability::Mut)?
2582 _ => return Ok(None),
2585 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2586 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2589 fn is_named_param(&self) -> bool {
2590 let offset = match self.token.kind {
2591 token::Interpolated(ref nt) => match **nt {
2592 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2595 token::BinOp(token::And) | token::AndAnd => 1,
2596 _ if self.token.is_keyword(kw::Mut) => 1,
2600 self.look_ahead(offset, |t| t.is_ident())
2601 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2604 fn recover_first_param(&mut self) -> &'static str {
2606 .parse_outer_attributes()
2607 .and_then(|_| self.parse_self_param())
2608 .map_err(|e| e.cancel())
2610 Ok(Some(_)) => "method",
2616 enum IsMacroRulesItem {
2617 Yes { has_bang: bool },