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};
6 use crate::errors::FnTypoWithImpl;
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::{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 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) =
226 self.parse_fn(attrs, fn_parse_mode, lo, vis, case)?;
227 (ident, ItemKind::Fn(Box::new(Fn { defaultness: def_(), sig, generics, body })))
228 } else if self.eat_keyword(kw::Extern) {
229 if self.eat_keyword(kw::Crate) {
231 self.parse_item_extern_crate()?
234 self.parse_item_foreign_mod(attrs, Unsafe::No)?
236 } else if self.is_unsafe_foreign_mod() {
238 let unsafety = self.parse_unsafety(Case::Sensitive);
239 self.expect_keyword(kw::Extern)?;
240 self.parse_item_foreign_mod(attrs, unsafety)?
241 } else if self.is_static_global() {
243 self.bump(); // `static`
244 let m = self.parse_mutability();
245 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
246 (ident, ItemKind::Static(ty, m, expr))
247 } else if let Const::Yes(const_span) = self.parse_constness(Case::Sensitive) {
249 if self.token.is_keyword(kw::Impl) {
250 // recover from `const impl`, suggest `impl const`
251 self.recover_const_impl(const_span, attrs, def_())?
253 self.recover_const_mut(const_span);
254 let (ident, ty, expr) = self.parse_item_global(None)?;
255 (ident, ItemKind::Const(def_(), ty, expr))
257 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
259 self.parse_item_trait(attrs, lo)?
260 } else if self.check_keyword(kw::Impl)
261 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
264 self.parse_item_impl(attrs, def_())?
265 } else if self.check_keyword(kw::Mod)
266 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
269 self.parse_item_mod(attrs)?
270 } else if self.eat_keyword(kw::Type) {
272 self.parse_type_alias(def_())?
273 } else if self.eat_keyword(kw::Enum) {
275 self.parse_item_enum()?
276 } else if self.eat_keyword(kw::Struct) {
278 self.parse_item_struct()?
279 } else if self.is_kw_followed_by_ident(kw::Union) {
281 self.bump(); // `union`
282 self.parse_item_union()?
283 } else if self.eat_keyword(kw::Macro) {
285 self.parse_item_decl_macro(lo)?
286 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
288 self.parse_item_macro_rules(vis, has_bang)?
289 } else if self.isnt_macro_invocation()
290 && (self.token.is_ident_named(sym::import)
291 || self.token.is_ident_named(sym::using)
292 || self.token.is_ident_named(sym::include)
293 || self.token.is_ident_named(sym::require))
295 return self.recover_import_as_use();
296 } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
297 self.recover_missing_kw_before_item()?;
299 } else if self.isnt_macro_invocation() && case == Case::Sensitive {
302 // Recover wrong cased keywords
303 return self.parse_item_kind(
312 } else if macros_allowed && self.check_path() {
313 // MACRO INVOCATION ITEM
314 (Ident::empty(), ItemKind::MacCall(P(self.parse_item_macro(vis)?)))
321 fn recover_import_as_use(&mut self) -> PResult<'a, Option<(Ident, ItemKind)>> {
322 let span = self.token.span;
323 let token_name = super::token_descr(&self.token);
324 let snapshot = self.create_snapshot_for_diagnostic();
326 match self.parse_use_item() {
328 self.struct_span_err(span, format!("expected item, found {token_name}"))
329 .span_suggestion_short(
331 "items are imported using the `use` keyword",
333 Applicability::MachineApplicable,
340 self.restore_snapshot(snapshot);
346 fn parse_use_item(&mut self) -> PResult<'a, (Ident, ItemKind)> {
347 let tree = self.parse_use_tree()?;
348 if let Err(mut e) = self.expect_semi() {
350 UseTreeKind::Glob => {
351 e.note("the wildcard token must be last on the path");
353 UseTreeKind::Nested(..) => {
354 e.note("glob-like brace syntax must be last on the path");
360 Ok((Ident::empty(), ItemKind::Use(tree)))
363 /// When parsing a statement, would the start of a path be an item?
364 pub(super) fn is_path_start_item(&mut self) -> bool {
365 self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
366 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
367 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
368 || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
371 /// Are we sure this could not possibly be a macro invocation?
372 fn isnt_macro_invocation(&mut self) -> bool {
373 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
376 /// Recover on encountering a struct or method definition where the user
377 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
378 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
379 // Space between `pub` keyword and the identifier
382 // ^^^ `sp` points here
383 let sp = self.prev_token.span.between(self.token.span);
384 let full_sp = self.prev_token.span.to(self.token.span);
385 let ident_sp = self.token.span;
386 if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace)) {
387 // possible public struct definition where `struct` was forgotten
388 let ident = self.parse_ident().unwrap();
389 let msg = format!("add `struct` here to parse `{ident}` as a public struct");
390 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
391 err.span_suggestion_short(
395 Applicability::MaybeIncorrect, // speculative
398 } else if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Parenthesis)) {
399 let ident = self.parse_ident().unwrap();
401 let kw_name = self.recover_first_param();
402 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::Yes);
403 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
404 self.eat_to_tokens(&[&token::OpenDelim(Delimiter::Brace)]);
406 ("fn", kw_name, false)
407 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
409 ("fn", kw_name, false)
410 } else if self.check(&token::Colon) {
414 ("fn` or `struct", "function or struct", true)
417 let msg = format!("missing `{kw}` for {kw_name} definition");
418 let mut err = self.struct_span_err(sp, &msg);
420 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
422 format!("add `{kw}` here to parse `{ident}` as a public {kw_name}");
423 err.span_suggestion_short(
427 Applicability::MachineApplicable,
429 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
432 "if you meant to call a macro, try",
433 format!("{}!", snippet),
434 // this is the `ambiguous` conditional branch
435 Applicability::MaybeIncorrect,
439 "if you meant to call a macro, remove the `pub` \
440 and add a trailing `!` after the identifier",
444 } else if self.look_ahead(1, |t| *t == token::Lt) {
445 let ident = self.parse_ident().unwrap();
446 self.eat_to_tokens(&[&token::Gt]);
448 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(Delimiter::Parenthesis)) {
449 ("fn", self.recover_first_param(), false)
450 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
451 ("struct", "struct", false)
453 ("fn` or `struct", "function or struct", true)
455 let msg = format!("missing `{kw}` for {kw_name} definition");
456 let mut err = self.struct_span_err(sp, &msg);
458 err.span_suggestion_short(
460 &format!("add `{kw}` here to parse `{ident}` as a public {kw_name}"),
462 Applicability::MachineApplicable,
471 /// Parses an item macro, e.g., `item!();`.
472 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
473 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
474 self.expect(&token::Not)?; // `!`
475 match self.parse_delim_args() {
476 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
478 self.eat_semi_for_macro_if_needed(&args);
479 self.complain_if_pub_macro(vis, false);
480 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
484 // Maybe the user misspelled `macro_rules` (issue #91227)
485 if self.token.is_ident()
486 && path.segments.len() == 1
487 && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
491 "perhaps you meant to define a macro",
493 Applicability::MachineApplicable,
501 /// Recover if we parsed attributes and expected an item but there was none.
502 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
503 let ([start @ end] | [start, .., end]) = attrs else {
506 let msg = if end.is_doc_comment() {
507 "expected item after doc comment"
509 "expected item after attributes"
511 let mut err = self.struct_span_err(end.span, msg);
512 if end.is_doc_comment() {
513 err.span_label(end.span, "this doc comment doesn't document anything");
515 if end.meta_kind().is_some() {
516 if self.token.kind == TokenKind::Semi {
517 err.span_suggestion_verbose(
519 "consider removing this semicolon",
521 Applicability::MaybeIncorrect,
525 if let [.., penultimate, _] = attrs {
526 err.span_label(start.span.to(penultimate.span), "other attributes here");
531 fn is_async_fn(&self) -> bool {
532 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
535 fn parse_polarity(&mut self) -> ast::ImplPolarity {
536 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
537 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
539 ast::ImplPolarity::Negative(self.prev_token.span)
541 ast::ImplPolarity::Positive
545 /// Parses an implementation item.
547 /// ```ignore (illustrative)
548 /// impl<'a, T> TYPE { /* impl items */ }
549 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
550 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
551 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
554 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
556 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
557 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
562 defaultness: Defaultness,
563 ) -> PResult<'a, ItemInfo> {
564 let unsafety = self.parse_unsafety(Case::Sensitive);
565 self.expect_keyword(kw::Impl)?;
567 // First, parse generic parameters if necessary.
568 let mut generics = if self.choose_generics_over_qpath(0) {
569 self.parse_generics()?
571 let mut generics = Generics::default();
573 // /\ this is where `generics.span` should point when there are no type params.
574 generics.span = self.prev_token.span.shrink_to_hi();
578 let constness = self.parse_constness(Case::Sensitive);
579 if let Const::Yes(span) = constness {
580 self.sess.gated_spans.gate(sym::const_trait_impl, span);
583 let polarity = self.parse_polarity();
585 // Parse both types and traits as a type, then reinterpret if necessary.
586 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
587 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
589 let span = self.prev_token.span.between(self.token.span);
590 self.struct_span_err(span, "missing trait in a trait impl")
595 Applicability::HasPlaceholders,
598 span.to(self.token.span),
599 "for an inherent impl, drop this `for`",
601 Applicability::MaybeIncorrect,
605 kind: TyKind::Path(None, err_path(span)),
611 self.parse_ty_with_generics_recovery(&generics)?
614 // If `for` is missing we try to recover.
615 let has_for = self.eat_keyword(kw::For);
616 let missing_for_span = self.prev_token.span.between(self.token.span);
618 let ty_second = if self.token == token::DotDot {
619 // We need to report this error after `cfg` expansion for compatibility reasons
620 self.bump(); // `..`, do not add it to expected tokens
621 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
622 } else if has_for || self.token.can_begin_type() {
623 Some(self.parse_ty()?)
628 generics.where_clause = self.parse_where_clause()?;
630 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
632 let item_kind = match ty_second {
634 // impl Trait for Type
636 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
637 .span_suggestion_short(
641 Applicability::MachineApplicable,
646 let ty_first = ty_first.into_inner();
647 let path = match ty_first.kind {
648 // This notably includes paths passed through `ty` macro fragments (#46438).
649 TyKind::Path(None, path) => path,
651 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
652 err_path(ty_first.span)
655 let trait_ref = TraitRef { path, ref_id: ty_first.id };
657 ItemKind::Impl(Box::new(Impl {
663 of_trait: Some(trait_ref),
670 ItemKind::Impl(Box::new(Impl {
683 Ok((Ident::empty(), item_kind))
686 fn parse_item_list<T>(
689 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
690 ) -> PResult<'a, Vec<T>> {
691 let open_brace_span = self.token.span;
693 // Recover `impl Ty;` instead of `impl Ty {}`
694 if self.token == TokenKind::Semi {
695 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
700 self.expect(&token::OpenDelim(Delimiter::Brace))?;
701 attrs.extend(self.parse_inner_attributes()?);
703 let mut items = Vec::new();
704 while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
705 if self.recover_doc_comment_before_brace() {
708 match parse_item(self) {
710 let mut is_unnecessary_semicolon = !items.is_empty()
711 // When the close delim is `)` in a case like the following, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
712 // but the actual `token.kind` is `token::CloseDelim(Delimiter::Brace)`.
713 // This is because the `token.kind` of the close delim is treated as the same as
714 // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
715 // Therefore, `token.kind` should not be compared here.
720 // fn qux() -> Option<usize> {
723 // ^ this close delim
728 .span_to_snippet(self.prev_token.span)
729 .map_or(false, |snippet| snippet == "}")
730 && self.token.kind == token::Semi;
731 let mut semicolon_span = self.token.span;
732 if !is_unnecessary_semicolon {
733 // #105369, Detect spurious `;` before assoc fn body
734 is_unnecessary_semicolon = self.token == token::OpenDelim(Delimiter::Brace)
735 && self.prev_token.kind == token::Semi;
736 semicolon_span = self.prev_token.span;
738 // We have to bail or we'll potentially never make progress.
739 let non_item_span = self.token.span;
740 let is_let = self.token.is_keyword(kw::Let);
742 let mut err = self.struct_span_err(non_item_span, "non-item in item list");
743 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
747 "consider using `const` instead of `let` for associated const",
749 Applicability::MachineApplicable,
752 err.span_label(open_brace_span, "item list starts here")
753 .span_label(non_item_span, "non-item starts here")
754 .span_label(self.prev_token.span, "item list ends here");
756 if is_unnecessary_semicolon {
759 "consider removing this semicolon",
761 Applicability::MaybeIncorrect,
767 Ok(Some(item)) => items.extend(item),
769 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
770 err.span_label(open_brace_span, "while parsing this item list starting here")
771 .span_label(self.prev_token.span, "the item list ends here")
780 /// Recover on a doc comment before `}`.
781 fn recover_doc_comment_before_brace(&mut self) -> bool {
782 if let token::DocComment(..) = self.token.kind {
783 if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
788 "found a documentation comment that doesn't document anything",
790 .span_label(self.token.span, "this doc comment doesn't document anything")
792 "doc comments must come before what they document, if a comment was \
803 /// Parses defaultness (i.e., `default` or nothing).
804 fn parse_defaultness(&mut self) -> Defaultness {
805 // We are interested in `default` followed by another identifier.
806 // However, we must avoid keywords that occur as binary operators.
807 // Currently, the only applicable keyword is `as` (`default as Ty`).
808 if self.check_keyword(kw::Default)
809 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
811 self.bump(); // `default`
812 Defaultness::Default(self.prev_token.uninterpolated_span())
818 /// Is this an `(unsafe auto? | auto) trait` item?
819 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
821 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
823 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
826 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
827 fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
828 let unsafety = self.parse_unsafety(Case::Sensitive);
829 // Parse optional `auto` prefix.
830 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
832 self.expect_keyword(kw::Trait)?;
833 let ident = self.parse_ident()?;
834 let mut generics = self.parse_generics()?;
836 // Parse optional colon and supertrait bounds.
837 let had_colon = self.eat(&token::Colon);
838 let span_at_colon = self.prev_token.span;
839 let bounds = if had_colon {
840 self.parse_generic_bounds(Some(self.prev_token.span))?
845 let span_before_eq = self.prev_token.span;
846 if self.eat(&token::Eq) {
847 // It's a trait alias.
849 let span = span_at_colon.to(span_before_eq);
850 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
853 let bounds = self.parse_generic_bounds(None)?;
854 generics.where_clause = self.parse_where_clause()?;
857 let whole_span = lo.to(self.prev_token.span);
858 if is_auto == IsAuto::Yes {
859 let msg = "trait aliases cannot be `auto`";
860 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
862 if let Unsafe::Yes(_) = unsafety {
863 let msg = "trait aliases cannot be `unsafe`";
864 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
867 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
869 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
871 // It's a normal trait.
872 generics.where_clause = self.parse_where_clause()?;
873 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
876 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
881 pub fn parse_impl_item(
883 force_collect: ForceCollect,
884 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
885 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
886 self.parse_assoc_item(fn_parse_mode, force_collect)
889 pub fn parse_trait_item(
891 force_collect: ForceCollect,
892 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
894 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
895 self.parse_assoc_item(fn_parse_mode, force_collect)
898 /// Parses associated items.
901 fn_parse_mode: FnParseMode,
902 force_collect: ForceCollect,
903 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
904 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
905 |Item { attrs, id, span, vis, ident, kind, tokens }| {
906 let kind = match AssocItemKind::try_from(kind) {
908 Err(kind) => match kind {
909 ItemKind::Static(a, _, b) => {
910 self.struct_span_err(span, "associated `static` items are not allowed")
912 AssocItemKind::Const(Defaultness::Final, a, b)
914 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
917 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
922 /// Parses a `type` alias with the following grammar:
924 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
926 /// The `"type"` has already been eaten.
927 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
928 let ident = self.parse_ident()?;
929 let mut generics = self.parse_generics()?;
931 // Parse optional colon and param bounds.
933 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
934 let before_where_clause = self.parse_where_clause()?;
936 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
938 let after_where_clause = self.parse_where_clause()?;
940 let where_clauses = (
941 TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
942 TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
944 let where_predicates_split = before_where_clause.predicates.len();
945 let mut predicates = before_where_clause.predicates;
946 predicates.extend(after_where_clause.predicates.into_iter());
947 let where_clause = WhereClause {
948 has_where_token: before_where_clause.has_where_token
949 || after_where_clause.has_where_token,
953 generics.where_clause = where_clause;
959 ItemKind::TyAlias(Box::new(TyAlias {
963 where_predicates_split,
970 /// Parses a `UseTree`.
973 /// USE_TREE = [`::`] `*` |
974 /// [`::`] `{` USE_TREE_LIST `}` |
976 /// PATH `::` `{` USE_TREE_LIST `}` |
977 /// PATH [`as` IDENT]
979 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
980 let lo = self.token.span;
983 ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo(), tokens: None };
984 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
985 || self.check(&token::BinOp(token::Star))
986 || self.is_import_coupler()
988 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
989 let mod_sep_ctxt = self.token.span.ctxt();
990 if self.eat(&token::ModSep) {
993 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
996 self.parse_use_tree_glob_or_nested()?
998 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
999 prefix = self.parse_path(PathStyle::Mod)?;
1001 if self.eat(&token::ModSep) {
1002 self.parse_use_tree_glob_or_nested()?
1004 // Recover from using a colon as path separator.
1005 while self.eat_noexpect(&token::Colon) {
1006 self.struct_span_err(self.prev_token.span, "expected `::`, found `:`")
1007 .span_suggestion_short(
1008 self.prev_token.span,
1011 Applicability::MachineApplicable,
1013 .note_once("import paths are delimited using `::`")
1016 // We parse the rest of the path and append it to the original prefix.
1017 self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1018 prefix.span = lo.to(self.prev_token.span);
1021 UseTreeKind::Simple(self.parse_rename()?)
1025 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
1028 /// Parses `*` or `{...}`.
1029 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1030 Ok(if self.eat(&token::BinOp(token::Star)) {
1033 UseTreeKind::Nested(self.parse_use_tree_list()?)
1037 /// Parses a `UseTreeKind::Nested(list)`.
1040 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
1042 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1043 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
1047 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1048 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1051 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1052 match self.token.ident() {
1053 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1057 _ => self.parse_ident(),
1061 /// Parses `extern crate` links.
1065 /// ```ignore (illustrative)
1066 /// extern crate foo;
1067 /// extern crate bar as foo;
1069 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1070 // Accept `extern crate name-like-this` for better diagnostics
1071 let orig_name = self.parse_crate_name_with_dashes()?;
1072 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1073 (rename, Some(orig_name.name))
1077 self.expect_semi()?;
1078 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1081 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1082 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1083 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1085 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1086 self.parse_path_segment_ident()
1090 let mut idents = vec![];
1091 let mut replacement = vec![];
1092 let mut fixed_crate_name = false;
1093 // Accept `extern crate name-like-this` for better diagnostics.
1094 let dash = token::BinOp(token::BinOpToken::Minus);
1095 if self.token == dash {
1096 // Do not include `-` as part of the expected tokens list.
1097 while self.eat(&dash) {
1098 fixed_crate_name = true;
1099 replacement.push((self.prev_token.span, "_".to_string()));
1100 idents.push(self.parse_ident()?);
1103 if fixed_crate_name {
1104 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1105 let mut fixed_name = ident.name.to_string();
1106 for part in idents {
1107 fixed_name.push_str(&format!("_{}", part.name));
1109 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1111 self.struct_span_err(fixed_name_sp, error_msg)
1112 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1113 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1119 /// Parses `extern` for foreign ABIs modules.
1121 /// `extern` is expected to have been consumed before calling this method.
1125 /// ```ignore (only-for-syntax-highlight)
1129 fn parse_item_foreign_mod(
1131 attrs: &mut AttrVec,
1132 mut unsafety: Unsafe,
1133 ) -> PResult<'a, ItemInfo> {
1134 let abi = self.parse_abi(); // ABI?
1135 if unsafety == Unsafe::No
1136 && self.token.is_keyword(kw::Unsafe)
1137 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1139 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1141 unsafety = Unsafe::Yes(self.token.span);
1142 self.eat_keyword(kw::Unsafe);
1144 let module = ast::ForeignMod {
1147 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1149 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1152 /// Parses a foreign item (one in an `extern { ... }` block).
1153 pub fn parse_foreign_item(
1155 force_collect: ForceCollect,
1156 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1157 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1158 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1159 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1160 let kind = match ForeignItemKind::try_from(kind) {
1162 Err(kind) => match kind {
1163 ItemKind::Const(_, a, b) => {
1164 self.error_on_foreign_const(span, ident);
1165 ForeignItemKind::Static(a, Mutability::Not, b)
1167 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1170 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1175 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1176 let span = self.sess.source_map().guess_head_span(span);
1177 let descr = kind.descr();
1178 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1179 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1184 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1185 self.struct_span_err(ident.span, "extern items cannot be `const`")
1187 span.with_hi(ident.span.lo()),
1188 "try using a static value",
1190 Applicability::MachineApplicable,
1192 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1196 fn is_unsafe_foreign_mod(&self) -> bool {
1197 self.token.is_keyword(kw::Unsafe)
1198 && self.is_keyword_ahead(1, &[kw::Extern])
1200 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1201 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1205 fn is_static_global(&mut self) -> bool {
1206 if self.check_keyword(kw::Static) {
1207 // Check if this could be a closure.
1208 !self.look_ahead(1, |token| {
1209 if token.is_keyword(kw::Move) {
1212 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1219 /// Recover on `const mut` with `const` already eaten.
1220 fn recover_const_mut(&mut self, const_span: Span) {
1221 if self.eat_keyword(kw::Mut) {
1222 let span = self.prev_token.span;
1223 self.struct_span_err(span, "const globals cannot be mutable")
1224 .span_label(span, "cannot be mutable")
1227 "you might want to declare a static instead",
1229 Applicability::MaybeIncorrect,
1232 } else if self.eat_keyword(kw::Let) {
1233 let span = self.prev_token.span;
1234 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1236 const_span.to(span),
1239 Applicability::MaybeIncorrect,
1245 /// Recover on `const impl` with `const` already eaten.
1246 fn recover_const_impl(
1249 attrs: &mut AttrVec,
1250 defaultness: Defaultness,
1251 ) -> PResult<'a, ItemInfo> {
1252 let impl_span = self.token.span;
1253 let mut err = self.expected_ident_found();
1255 // Only try to recover if this is implementing a trait for a type
1256 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1257 Ok(impl_info) => impl_info,
1258 Err(recovery_error) => {
1259 // Recovery failed, raise the "expected identifier" error
1260 recovery_error.cancel();
1265 match &mut impl_info.1 {
1266 ItemKind::Impl(box Impl { of_trait: Some(trai), constness, .. }) => {
1267 *constness = Const::Yes(const_span);
1269 let before_trait = trai.path.span.shrink_to_lo();
1270 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1271 err.multipart_suggestion(
1272 "you might have meant to write a const trait impl",
1273 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1274 Applicability::MaybeIncorrect,
1278 ItemKind::Impl { .. } => return Err(err),
1279 _ => unreachable!(),
1285 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1286 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1288 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1289 fn parse_item_global(
1291 m: Option<Mutability>,
1292 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1293 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1295 // Parse the type of a `const` or `static mut?` item.
1296 // That is, the `":" $ty` fragment.
1297 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1299 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1300 (true, false) => self.parse_ty()?,
1301 (colon, _) => self.recover_missing_const_type(colon, m),
1304 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1305 self.expect_semi()?;
1309 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1310 /// This means that the type is missing.
1311 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1312 // Construct the error and stash it away with the hope
1313 // that typeck will later enrich the error with a type.
1314 let kind = match m {
1315 Some(Mutability::Mut) => "static mut",
1316 Some(Mutability::Not) => "static",
1320 let colon = match colon_present {
1325 let span = self.prev_token.span.shrink_to_hi();
1326 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1327 err.span_suggestion(
1329 "provide a type for the item",
1330 format!("{colon} <type>"),
1331 Applicability::HasPlaceholders,
1333 err.stash(span, StashKey::ItemNoType);
1335 // The user intended that the type be inferred,
1336 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1337 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1340 /// Parses an enum declaration.
1341 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1342 if self.token.is_keyword(kw::Struct) {
1343 let span = self.prev_token.span.to(self.token.span);
1344 let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1345 err.span_suggestion(
1347 "replace `enum struct` with",
1349 Applicability::MachineApplicable,
1351 if self.look_ahead(1, |t| t.is_ident()) {
1359 let id = self.parse_ident()?;
1360 let mut generics = self.parse_generics()?;
1361 generics.where_clause = self.parse_where_clause()?;
1363 // Possibly recover `enum Foo;` instead of `enum Foo {}`
1364 let (variants, _) = if self.token == TokenKind::Semi {
1365 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1369 self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1371 e.span_label(id.span, "while parsing this enum");
1372 self.recover_stmt();
1378 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1379 Ok((id, ItemKind::Enum(enum_definition, generics)))
1382 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1383 let variant_attrs = self.parse_outer_attributes()?;
1384 self.collect_tokens_trailing_token(
1387 |this, variant_attrs| {
1388 let vlo = this.token.span;
1390 let vis = this.parse_visibility(FollowedByType::No)?;
1391 if !this.recover_nested_adt_item(kw::Enum)? {
1392 return Ok((None, TrailingToken::None));
1394 let ident = this.parse_field_ident("enum", vlo)?;
1396 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1397 // Parse a struct variant.
1398 let (fields, recovered) =
1399 this.parse_record_struct_body("struct", ident.span, false)?;
1400 VariantData::Struct(fields, recovered)
1401 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1402 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1404 VariantData::Unit(DUMMY_NODE_ID)
1408 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1410 let vr = ast::Variant {
1414 attrs: variant_attrs,
1417 span: vlo.to(this.prev_token.span),
1418 is_placeholder: false,
1421 Ok((Some(vr), TrailingToken::MaybeComma))
1423 ).map_err(|mut err|{
1424 err.help("enum variants can be `Variant`, `Variant = <integer>`, `Variant(Type, ..., TypeN)` or `Variant { fields: Types }`");
1429 /// Parses `struct Foo { ... }`.
1430 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1431 let class_name = self.parse_ident()?;
1433 let mut generics = self.parse_generics()?;
1435 // There is a special case worth noting here, as reported in issue #17904.
1436 // If we are parsing a tuple struct it is the case that the where clause
1437 // should follow the field list. Like so:
1439 // struct Foo<T>(T) where T: Copy;
1441 // If we are parsing a normal record-style struct it is the case
1442 // that the where clause comes before the body, and after the generics.
1443 // So if we look ahead and see a brace or a where-clause we begin
1444 // parsing a record style struct.
1446 // Otherwise if we look ahead and see a paren we parse a tuple-style
1449 let vdata = if self.token.is_keyword(kw::Where) {
1450 generics.where_clause = self.parse_where_clause()?;
1451 if self.eat(&token::Semi) {
1452 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1453 VariantData::Unit(DUMMY_NODE_ID)
1455 // If we see: `struct Foo<T> where T: Copy { ... }`
1456 let (fields, recovered) = self.parse_record_struct_body(
1459 generics.where_clause.has_where_token,
1461 VariantData::Struct(fields, recovered)
1463 // No `where` so: `struct Foo<T>;`
1464 } else if self.eat(&token::Semi) {
1465 VariantData::Unit(DUMMY_NODE_ID)
1466 // Record-style struct definition
1467 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1468 let (fields, recovered) = self.parse_record_struct_body(
1471 generics.where_clause.has_where_token,
1473 VariantData::Struct(fields, recovered)
1474 // Tuple-style struct definition with optional where-clause.
1475 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1476 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1477 generics.where_clause = self.parse_where_clause()?;
1478 self.expect_semi()?;
1481 let token_str = super::token_descr(&self.token);
1483 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1485 let mut err = self.struct_span_err(self.token.span, msg);
1486 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1490 Ok((class_name, ItemKind::Struct(vdata, generics)))
1493 /// Parses `union Foo { ... }`.
1494 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1495 let class_name = self.parse_ident()?;
1497 let mut generics = self.parse_generics()?;
1499 let vdata = if self.token.is_keyword(kw::Where) {
1500 generics.where_clause = self.parse_where_clause()?;
1501 let (fields, recovered) = self.parse_record_struct_body(
1504 generics.where_clause.has_where_token,
1506 VariantData::Struct(fields, recovered)
1507 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1508 let (fields, recovered) = self.parse_record_struct_body(
1511 generics.where_clause.has_where_token,
1513 VariantData::Struct(fields, recovered)
1515 let token_str = super::token_descr(&self.token);
1516 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1517 let mut err = self.struct_span_err(self.token.span, msg);
1518 err.span_label(self.token.span, "expected `where` or `{` after union name");
1522 Ok((class_name, ItemKind::Union(vdata, generics)))
1525 fn parse_record_struct_body(
1530 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1531 let mut fields = Vec::new();
1532 let mut recovered = false;
1533 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1534 while self.token != token::CloseDelim(Delimiter::Brace) {
1535 let field = self.parse_field_def(adt_ty).map_err(|e| {
1536 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1541 Ok(field) => fields.push(field),
1543 err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1549 self.eat(&token::CloseDelim(Delimiter::Brace));
1551 let token_str = super::token_descr(&self.token);
1553 "expected {}`{{` after struct name, found {}",
1554 if parsed_where { "" } else { "`where`, or " },
1557 let mut err = self.struct_span_err(self.token.span, msg);
1561 "expected {}`{{` after struct name",
1562 if parsed_where { "" } else { "`where`, or " }
1568 Ok((fields, recovered))
1571 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1572 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1573 // Unit like structs are handled in parse_item_struct function
1574 self.parse_paren_comma_seq(|p| {
1575 let attrs = p.parse_outer_attributes()?;
1576 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1577 let lo = p.token.span;
1578 let vis = p.parse_visibility(FollowedByType::Yes)?;
1579 let ty = p.parse_ty()?;
1583 span: lo.to(ty.span),
1589 is_placeholder: false,
1591 TrailingToken::MaybeComma,
1598 /// Parses an element of a struct declaration.
1599 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1600 let attrs = self.parse_outer_attributes()?;
1601 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1602 let lo = this.token.span;
1603 let vis = this.parse_visibility(FollowedByType::No)?;
1604 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1608 /// Parses a structure field declaration.
1609 fn parse_single_struct_field(
1615 ) -> PResult<'a, FieldDef> {
1616 let mut seen_comma: bool = false;
1617 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1618 if self.token == token::Comma {
1621 if self.eat(&token::Semi) {
1622 let sp = self.prev_token.span;
1623 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1624 err.span_suggestion_short(
1626 "replace `;` with `,`",
1628 Applicability::MachineApplicable,
1632 match self.token.kind {
1636 token::CloseDelim(Delimiter::Brace) => {}
1637 token::DocComment(..) => {
1638 let previous_span = self.prev_token.span;
1639 let mut err = DocCommentDoesNotDocumentAnything {
1640 span: self.token.span,
1641 missing_comma: None,
1643 self.bump(); // consume the doc comment
1644 let comma_after_doc_seen = self.eat(&token::Comma);
1645 // `seen_comma` is always false, because we are inside doc block
1646 // condition is here to make code more readable
1647 if !seen_comma && comma_after_doc_seen {
1650 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1651 self.sess.emit_err(err);
1654 let sp = previous_span.shrink_to_hi();
1655 err.missing_comma = Some(sp);
1657 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1661 let sp = self.prev_token.span.shrink_to_hi();
1662 let mut err = self.struct_span_err(
1664 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1667 // Try to recover extra trailing angle brackets
1668 let mut recovered = false;
1669 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1670 if let Some(last_segment) = segments.last() {
1671 recovered = self.check_trailing_angle_brackets(
1673 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1676 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1678 self.eat(&token::Comma);
1679 // `check_trailing_angle_brackets` already emitted a nicer error
1680 // NOTE(eddyb) this was `.cancel()`, but `err`
1681 // gets returned, so we can't fully defuse it.
1687 if self.token.is_ident()
1688 || (self.token.kind == TokenKind::Pound
1689 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1691 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1692 // emit the diagnostic and keep going
1693 err.span_suggestion(
1695 "try adding a comma",
1697 Applicability::MachineApplicable,
1704 // Make sure an error was emitted (either by recovering an angle bracket,
1705 // or by finding an identifier as the next token), since we're
1706 // going to continue parsing
1707 assert!(self.sess.span_diagnostic.has_errors().is_some());
1716 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1717 if let Err(mut err) = self.expect(&token::Colon) {
1718 let sm = self.sess.source_map();
1719 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1720 let semi_typo = self.token.kind == token::Semi
1721 && self.look_ahead(1, |t| {
1723 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1724 // when there's no type and `;` was used instead of a comma.
1725 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1726 (Ok(l), Ok(r)) => l.line == r.line,
1730 if eq_typo || semi_typo {
1732 // Gracefully handle small typos.
1733 err.span_suggestion_short(
1734 self.prev_token.span,
1735 "field names and their types are separated with `:`",
1737 Applicability::MachineApplicable,
1747 /// Parses a structure field.
1748 fn parse_name_and_ty(
1754 ) -> PResult<'a, FieldDef> {
1755 let name = self.parse_field_ident(adt_ty, lo)?;
1756 self.expect_field_ty_separator()?;
1757 let ty = self.parse_ty()?;
1758 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1759 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1760 .span_suggestion_verbose(
1762 "write a path separator here",
1764 Applicability::MaybeIncorrect,
1768 if self.token.kind == token::Eq {
1770 let const_expr = self.parse_anon_const_expr()?;
1771 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1772 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1775 "remove this unsupported default value",
1777 Applicability::MachineApplicable,
1782 span: lo.to(self.prev_token.span),
1788 is_placeholder: false,
1792 /// Parses a field identifier. Specialized version of `parse_ident_common`
1793 /// for better diagnostics and suggestions.
1794 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1795 let (ident, is_raw) = self.ident_or_err()?;
1796 if !is_raw && ident.is_reserved() {
1797 let snapshot = self.create_snapshot_for_diagnostic();
1798 let err = if self.check_fn_front_matter(false, Case::Sensitive) {
1799 let inherited_vis = Visibility {
1800 span: rustc_span::DUMMY_SP,
1801 kind: VisibilityKind::Inherited,
1804 // We use `parse_fn` to get a span for the function
1805 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1806 match self.parse_fn(
1807 &mut AttrVec::new(),
1814 let mut err = self.struct_span_err(
1815 lo.to(self.prev_token.span),
1816 &format!("functions are not allowed in {adt_ty} definitions"),
1819 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1821 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1826 self.restore_snapshot(snapshot);
1827 self.expected_ident_found()
1830 } else if self.eat_keyword(kw::Struct) {
1831 match self.parse_item_struct() {
1833 let mut err = self.struct_span_err(
1834 lo.with_hi(ident.span.hi()),
1835 &format!("structs are not allowed in {adt_ty} definitions"),
1837 err.help("consider creating a new `struct` definition instead of nesting");
1842 self.restore_snapshot(snapshot);
1843 self.expected_ident_found()
1847 let mut err = self.expected_ident_found();
1848 if self.eat_keyword_noexpect(kw::Let)
1849 && let removal_span = self.prev_token.span.until(self.token.span)
1850 && let Ok(ident) = self.parse_ident_common(false)
1851 // Cancel this error, we don't need it.
1852 .map_err(|err| err.cancel())
1853 && self.token.kind == TokenKind::Colon
1855 err.span_suggestion(
1857 "remove this `let` keyword",
1859 Applicability::MachineApplicable,
1861 err.note("the `let` keyword is not allowed in `struct` fields");
1862 err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1866 self.restore_snapshot(snapshot);
1876 /// Parses a declarative macro 2.0 definition.
1877 /// The `macro` keyword has already been parsed.
1879 /// MacBody = "{" TOKEN_STREAM "}" ;
1880 /// MacParams = "(" TOKEN_STREAM ")" ;
1881 /// DeclMac = "macro" Ident MacParams? MacBody ;
1883 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1884 let ident = self.parse_ident()?;
1885 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1886 self.parse_delim_args()? // `MacBody`
1887 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1888 let params = self.parse_token_tree(); // `MacParams`
1889 let pspan = params.span();
1890 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1891 return self.unexpected();
1893 let body = self.parse_token_tree(); // `MacBody`
1894 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1895 let bspan = body.span();
1896 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1897 let tokens = TokenStream::new(vec![params, arrow, body]);
1898 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1899 P(DelimArgs { dspan, delim: MacDelimiter::Brace, tokens })
1901 return self.unexpected();
1904 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1905 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1908 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1909 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1910 if self.check_keyword(kw::MacroRules) {
1911 let macro_rules_span = self.token.span;
1913 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1914 return IsMacroRulesItem::Yes { has_bang: true };
1915 } else if self.look_ahead(1, |t| (t.is_ident())) {
1917 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1922 Applicability::MachineApplicable,
1926 return IsMacroRulesItem::Yes { has_bang: false };
1930 IsMacroRulesItem::No
1933 /// Parses a `macro_rules! foo { ... }` declarative macro.
1934 fn parse_item_macro_rules(
1938 ) -> PResult<'a, ItemInfo> {
1939 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1942 self.expect(&token::Not)?; // `!`
1944 let ident = self.parse_ident()?;
1946 if self.eat(&token::Not) {
1947 // Handle macro_rules! foo!
1948 let span = self.prev_token.span;
1949 self.struct_span_err(span, "macro names aren't followed by a `!`")
1950 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1954 let body = self.parse_delim_args()?;
1955 self.eat_semi_for_macro_if_needed(&body);
1956 self.complain_if_pub_macro(vis, true);
1958 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1961 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1962 /// If that's not the case, emit an error.
1963 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1964 if let VisibilityKind::Inherited = vis.kind {
1968 let vstr = pprust::vis_to_string(vis);
1969 let vstr = vstr.trim_end();
1971 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1972 self.struct_span_err(vis.span, &msg)
1975 "try exporting the macro",
1977 Applicability::MaybeIncorrect, // speculative
1981 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1984 "remove the visibility",
1986 Applicability::MachineApplicable,
1988 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1993 fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs) {
1994 if args.need_semicolon() && !self.eat(&token::Semi) {
1995 self.report_invalid_macro_expansion_item(args);
1999 fn report_invalid_macro_expansion_item(&self, args: &DelimArgs) {
2000 let span = args.dspan.entire();
2001 let mut err = self.struct_span_err(
2003 "macros that expand to items must be delimited with braces or followed by a semicolon",
2005 // FIXME: This will make us not emit the help even for declarative
2006 // macros within the same crate (that we can fix), which is sad.
2007 if !span.from_expansion() {
2008 if self.unclosed_delims.is_empty() {
2009 let DelimSpan { open, close } = args.dspan;
2010 err.multipart_suggestion(
2011 "change the delimiters to curly braces",
2012 vec![(open, "{".to_string()), (close, '}'.to_string())],
2013 Applicability::MaybeIncorrect,
2016 err.span_suggestion(
2018 "change the delimiters to curly braces",
2020 Applicability::HasPlaceholders,
2023 err.span_suggestion(
2024 span.shrink_to_hi(),
2027 Applicability::MaybeIncorrect,
2033 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2034 /// it is, we try to parse the item and report error about nested types.
2035 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2036 if (self.token.is_keyword(kw::Enum)
2037 || self.token.is_keyword(kw::Struct)
2038 || self.token.is_keyword(kw::Union))
2039 && self.look_ahead(1, |t| t.is_ident())
2041 let kw_token = self.token.clone();
2042 let kw_str = pprust::token_to_string(&kw_token);
2043 let item = self.parse_item(ForceCollect::No)?;
2045 self.struct_span_err(
2047 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
2051 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2053 Applicability::MaybeIncorrect,
2056 // We successfully parsed the item but we must inform the caller about nested problem.
2063 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2065 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2067 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2068 /// were allowed to omit parameter names. In 2018, they became required.
2069 type ReqName = fn(Edition) -> bool;
2071 /// Parsing configuration for functions.
2073 /// The syntax of function items is slightly different within trait definitions,
2074 /// impl blocks, and modules. It is still parsed using the same code, just with
2075 /// different flags set, so that even when the input is wrong and produces a parse
2076 /// error, it still gets into the AST and the rest of the parser and
2077 /// type checker can run.
2078 #[derive(Clone, Copy)]
2079 pub(crate) struct FnParseMode {
2080 /// A function pointer that decides if, per-parameter `p`, `p` must have a
2081 /// pattern or just a type. This field affects parsing of the parameters list.
2084 /// fn foo(alef: A) -> X { X::new() }
2085 /// -----^^ affects parsing this part of the function signature
2087 /// if req_name returns false, then this name is optional
2092 /// if req_name returns true, this is an error
2095 /// Calling this function pointer should only return false if:
2097 /// * The item is being parsed inside of a trait definition.
2098 /// Within an impl block or a module, it should always evaluate
2100 /// * The span is from Edition 2015. In particular, you can get a
2101 /// 2015 span inside a 2021 crate using macros.
2102 pub req_name: ReqName,
2103 /// If this flag is set to `true`, then plain, semicolon-terminated function
2104 /// prototypes are not allowed here.
2107 /// fn foo(alef: A) -> X { X::new() }
2110 /// this is always allowed
2112 /// fn bar(alef: A, bet: B) -> X;
2115 /// if req_body is set to true, this is an error
2118 /// This field should only be set to false if the item is inside of a trait
2119 /// definition or extern block. Within an impl block or a module, it should
2120 /// always be set to true.
2124 /// Parsing of functions and methods.
2125 impl<'a> Parser<'a> {
2126 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2129 attrs: &mut AttrVec,
2130 fn_parse_mode: FnParseMode,
2134 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2135 let fn_span = self.token.span;
2136 let header = self.parse_fn_front_matter(vis, case)?; // `const ... fn`
2137 let ident = self.parse_ident()?; // `foo`
2138 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2139 let decl = match self.parse_fn_decl(
2140 fn_parse_mode.req_name,
2142 RecoverReturnSign::Yes,
2146 // If we see `for Ty ...` then user probably meant `impl` item.
2147 if self.token.is_keyword(kw::For) {
2149 return Err(self.sess.create_err(FnTypoWithImpl { fn_span }));
2151 return Err(old_err);
2155 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2157 let mut sig_hi = self.prev_token.span;
2158 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2159 let fn_sig_span = sig_lo.to(sig_hi);
2160 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2163 /// Parse the "body" of a function.
2164 /// This can either be `;` when there's no body,
2165 /// or e.g. a block when the function is a provided one.
2168 attrs: &mut AttrVec,
2172 ) -> PResult<'a, Option<P<Block>>> {
2173 let has_semi = if req_body {
2174 self.token.kind == TokenKind::Semi
2176 // Only include `;` in list of expected tokens if body is not required
2177 self.check(&TokenKind::Semi)
2179 let (inner_attrs, body) = if has_semi {
2180 // Include the trailing semicolon in the span of the signature
2181 self.expect_semi()?;
2182 *sig_hi = self.prev_token.span;
2183 (AttrVec::new(), None)
2184 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2185 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2186 } else if self.token.kind == token::Eq {
2187 // Recover `fn foo() = $expr;`.
2189 let eq_sp = self.prev_token.span;
2190 let _ = self.parse_expr()?;
2191 self.expect_semi()?; // `;`
2192 let span = eq_sp.to(self.prev_token.span);
2193 self.struct_span_err(span, "function body cannot be `= expression;`")
2194 .multipart_suggestion(
2195 "surround the expression with `{` and `}` instead of `=` and `;`",
2196 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2197 Applicability::MachineApplicable,
2200 (AttrVec::new(), Some(self.mk_block_err(span)))
2202 let expected = if req_body {
2203 &[token::OpenDelim(Delimiter::Brace)][..]
2205 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2207 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2208 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2209 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2210 // the AST for typechecking.
2211 err.span_label(ident.span, "while parsing this `fn`");
2217 (AttrVec::new(), None)
2219 attrs.extend(inner_attrs);
2223 /// Is the current token the start of an `FnHeader` / not a valid parse?
2225 /// `check_pub` adds additional `pub` to the checks in case users place it
2226 /// wrongly, can be used to ensure `pub` never comes after `default`.
2227 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2228 // We use an over-approximation here.
2229 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2230 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2231 // only if it wasn't preceded by `default` as `default pub` is invalid.
2232 let quals: &[Symbol] = if check_pub {
2233 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2235 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2237 self.check_keyword_case(kw::Fn, case) // Definitely an `fn`.
2238 // `$qual fn` or `$qual $qual`:
2239 || quals.iter().any(|&kw| self.check_keyword_case(kw, case))
2240 && self.look_ahead(1, |t| {
2241 // `$qual fn`, e.g. `const fn` or `async fn`.
2242 t.is_keyword_case(kw::Fn, case)
2243 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2246 t.is_non_raw_ident_where(|i|
2247 quals.contains(&i.name)
2248 // Rule out 2015 `const async: T = val`.
2251 || case == Case::Insensitive
2252 && t.is_non_raw_ident_where(|i| quals.iter().any(|qual| qual.as_str() == i.name.as_str().to_lowercase()))
2254 // Rule out unsafe extern block.
2255 && !self.is_unsafe_foreign_mod())
2258 || self.check_keyword_case(kw::Extern, case)
2259 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2260 && self.look_ahead(2, |t| t.is_keyword_case(kw::Fn, case))
2263 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2264 /// up to and including the `fn` keyword. The formal grammar is:
2267 /// Extern = "extern" StringLit? ;
2268 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2269 /// FnFrontMatter = FnQual "fn" ;
2272 /// `vis` represents the visibility that was already parsed, if any. Use
2273 /// `Visibility::Inherited` when no visibility is known.
2274 pub(super) fn parse_fn_front_matter(
2276 orig_vis: &Visibility,
2278 ) -> PResult<'a, FnHeader> {
2279 let sp_start = self.token.span;
2280 let constness = self.parse_constness(case);
2282 let async_start_sp = self.token.span;
2283 let asyncness = self.parse_asyncness(case);
2285 let unsafe_start_sp = self.token.span;
2286 let unsafety = self.parse_unsafety(case);
2288 let ext_start_sp = self.token.span;
2289 let ext = self.parse_extern(case);
2291 if let Async::Yes { span, .. } = asyncness {
2292 self.ban_async_in_2015(span);
2295 if !self.eat_keyword_case(kw::Fn, case) {
2296 // It is possible for `expect_one_of` to recover given the contents of
2297 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2298 // account for this.
2299 match self.expect_one_of(&[], &[]) {
2301 Ok(false) => unreachable!(),
2303 // Qualifier keywords ordering check
2309 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2310 // that the keyword is already present and the second instance should be removed.
2311 let wrong_kw = if self.check_keyword(kw::Const) {
2313 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2314 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2316 } else if self.check_keyword(kw::Async) {
2318 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2319 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2321 } else if self.check_keyword(kw::Unsafe) {
2323 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2324 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2330 // The keyword is already present, suggest removal of the second instance
2331 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2332 let original_kw = self
2333 .span_to_snippet(original_sp)
2334 .expect("Span extracted directly from keyword should always work");
2336 err.span_suggestion(
2337 self.token.uninterpolated_span(),
2338 &format!("`{original_kw}` already used earlier, remove this one"),
2340 Applicability::MachineApplicable,
2342 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2344 // The keyword has not been seen yet, suggest correct placement in the function front matter
2345 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2346 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2347 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2348 let misplaced_qual_sp = self.token.uninterpolated_span();
2349 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2351 err.span_suggestion(
2352 correct_pos_sp.to(misplaced_qual_sp),
2353 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2354 format!("{misplaced_qual} {current_qual}"),
2355 Applicability::MachineApplicable,
2356 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2359 // Recover incorrect visibility order such as `async pub`
2360 else if self.check_keyword(kw::Pub) {
2361 let sp = sp_start.to(self.prev_token.span);
2362 if let Ok(snippet) = self.span_to_snippet(sp) {
2363 let current_vis = match self.parse_visibility(FollowedByType::No) {
2370 let vs = pprust::vis_to_string(¤t_vis);
2371 let vs = vs.trim_end();
2373 // There was no explicit visibility
2374 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2375 err.span_suggestion(
2376 sp_start.to(self.prev_token.span),
2377 &format!("visibility `{vs}` must come before `{snippet}`"),
2378 format!("{vs} {snippet}"),
2379 Applicability::MachineApplicable,
2382 // There was an explicit visibility
2384 err.span_suggestion(
2386 "there is already a visibility modifier, remove one",
2388 Applicability::MachineApplicable,
2390 .span_note(orig_vis.span, "explicit visibility first seen here");
2399 Ok(FnHeader { constness, unsafety, asyncness, ext })
2402 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2403 fn ban_async_in_2015(&self, span: Span) {
2404 if span.rust_2015() {
2405 let diag = self.diagnostic();
2406 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2407 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2408 .help_use_latest_edition()
2413 /// Parses the parameter list and result type of a function declaration.
2414 pub(super) fn parse_fn_decl(
2417 ret_allow_plus: AllowPlus,
2418 recover_return_sign: RecoverReturnSign,
2419 ) -> PResult<'a, P<FnDecl>> {
2421 inputs: self.parse_fn_params(req_name)?,
2422 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2426 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2427 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2428 let mut first_param = true;
2429 // Parse the arguments, starting out with `self` being allowed...
2430 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2431 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2433 let lo = p.prev_token.span;
2434 // Skip every token until next possible arg or end.
2435 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2436 // Create a placeholder argument for proper arg count (issue #34264).
2437 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2439 // ...now that we've parsed the first argument, `self` is no longer allowed.
2440 first_param = false;
2443 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2444 self.deduplicate_recovered_params_names(&mut params);
2448 /// Parses a single function parameter.
2450 /// - `self` is syntactically allowed when `first_param` holds.
2451 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2452 let lo = self.token.span;
2453 let attrs = self.parse_outer_attributes()?;
2454 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2455 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2456 if let Some(mut param) = this.parse_self_param()? {
2457 param.attrs = attrs;
2458 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2459 return Ok((res?, TrailingToken::None));
2462 let is_name_required = match this.token.kind {
2463 token::DotDotDot => false,
2464 _ => req_name(this.token.span.edition()),
2466 let (pat, ty) = if is_name_required || this.is_named_param() {
2467 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2469 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2471 let mut err = this.unexpected::<()>().unwrap_err();
2472 return if let Some(ident) =
2473 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2476 Ok((dummy_arg(ident), TrailingToken::None))
2482 this.eat_incorrect_doc_comment_for_param_type();
2483 (pat, this.parse_ty_for_param()?)
2485 debug!("parse_param_general ident_to_pat");
2486 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2487 this.eat_incorrect_doc_comment_for_param_type();
2488 let mut ty = this.parse_ty_for_param();
2490 && this.token != token::Comma
2491 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2493 // This wasn't actually a type, but a pattern looking like a type,
2494 // so we are going to rollback and re-parse for recovery.
2495 ty = this.unexpected();
2499 let ident = Ident::new(kw::Empty, this.prev_token.span);
2500 let bm = BindingAnnotation::NONE;
2501 let pat = this.mk_pat_ident(ty.span, bm, ident);
2504 // If this is a C-variadic argument and we hit an error, return the error.
2505 Err(err) if this.token == token::DotDotDot => return Err(err),
2506 // Recover from attempting to parse the argument as a type without pattern.
2509 this.restore_snapshot(parser_snapshot_before_ty);
2510 this.recover_arg_parse()?
2515 let span = lo.to(this.prev_token.span);
2518 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2519 TrailingToken::None,
2524 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2525 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2526 // Extract an identifier *after* having confirmed that the token is one.
2527 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2528 Some((ident, false)) => {
2532 _ => unreachable!(),
2534 // Is `self` `n` tokens ahead?
2535 let is_isolated_self = |this: &Self, n| {
2536 this.is_keyword_ahead(n, &[kw::SelfLower])
2537 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2539 // Is `mut self` `n` tokens ahead?
2540 let is_isolated_mut_self =
2541 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2542 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2543 let parse_self_possibly_typed = |this: &mut Self, m| {
2544 let eself_ident = expect_self_ident(this);
2545 let eself_hi = this.prev_token.span;
2546 let eself = if this.eat(&token::Colon) {
2547 SelfKind::Explicit(this.parse_ty()?, m)
2551 Ok((eself, eself_ident, eself_hi))
2553 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2554 let recover_self_ptr = |this: &mut Self| {
2555 let msg = "cannot pass `self` by raw pointer";
2556 let span = this.token.span;
2557 this.struct_span_err(span, msg).span_label(span, msg).emit();
2559 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2562 // Parse optional `self` parameter of a method.
2563 // Only a limited set of initial token sequences is considered `self` parameters; anything
2564 // else is parsed as a normal function parameter list, so some lookahead is required.
2565 let eself_lo = self.token.span;
2566 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2567 token::BinOp(token::And) => {
2568 let eself = if is_isolated_self(self, 1) {
2571 SelfKind::Region(None, Mutability::Not)
2572 } else if is_isolated_mut_self(self, 1) {
2576 SelfKind::Region(None, Mutability::Mut)
2577 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2580 let lt = self.expect_lifetime();
2581 SelfKind::Region(Some(lt), Mutability::Not)
2582 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2585 let lt = self.expect_lifetime();
2587 SelfKind::Region(Some(lt), Mutability::Mut)
2592 (eself, expect_self_ident(self), self.prev_token.span)
2595 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2597 recover_self_ptr(self)?
2599 // `*mut self` and `*const self`
2600 token::BinOp(token::Star)
2601 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2605 recover_self_ptr(self)?
2607 // `self` and `self: TYPE`
2608 token::Ident(..) if is_isolated_self(self, 0) => {
2609 parse_self_possibly_typed(self, Mutability::Not)?
2611 // `mut self` and `mut self: TYPE`
2612 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2614 parse_self_possibly_typed(self, Mutability::Mut)?
2616 _ => return Ok(None),
2619 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2620 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2623 fn is_named_param(&self) -> bool {
2624 let offset = match &self.token.kind {
2625 token::Interpolated(nt) => match **nt {
2626 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2629 token::BinOp(token::And) | token::AndAnd => 1,
2630 _ if self.token.is_keyword(kw::Mut) => 1,
2634 self.look_ahead(offset, |t| t.is_ident())
2635 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2638 fn recover_first_param(&mut self) -> &'static str {
2640 .parse_outer_attributes()
2641 .and_then(|_| self.parse_self_param())
2642 .map_err(|e| e.cancel())
2644 Ok(Some(_)) => "method",
2650 enum IsMacroRulesItem {
2651 Yes { has_bang: bool },