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;
29 /// Parses a source module as a crate. This is the main entry point for the parser.
30 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
31 let (attrs, items, spans) = self.parse_mod(&token::Eof)?;
32 Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
35 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
36 fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemInfo> {
37 let unsafety = self.parse_unsafety(Case::Sensitive);
38 self.expect_keyword(kw::Mod)?;
39 let id = self.parse_ident()?;
40 let mod_kind = if self.eat(&token::Semi) {
43 self.expect(&token::OpenDelim(Delimiter::Brace))?;
44 let (inner_attrs, items, inner_span) =
45 self.parse_mod(&token::CloseDelim(Delimiter::Brace))?;
46 attrs.extend(inner_attrs);
47 ModKind::Loaded(items, Inline::Yes, inner_span)
49 Ok((id, ItemKind::Mod(unsafety, mod_kind)))
52 /// Parses the contents of a module (inner attributes followed by module items).
56 ) -> PResult<'a, (AttrVec, Vec<P<Item>>, ModSpans)> {
57 let lo = self.token.span;
58 let attrs = self.parse_inner_attributes()?;
60 let post_attr_lo = self.token.span;
61 let mut items = vec![];
62 while let Some(item) = self.parse_item(ForceCollect::No)? {
64 self.maybe_consume_incorrect_semicolon(&items);
68 let token_str = super::token_descr(&self.token);
69 if !self.maybe_consume_incorrect_semicolon(&items) {
70 let msg = &format!("expected item, found {token_str}");
71 let mut err = self.struct_span_err(self.token.span, msg);
72 let label = if self.is_kw_followed_by_ident(kw::Let) {
73 "consider using `const` or `static` instead of `let` for global variables"
77 err.span_label(self.token.span, label);
82 let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
83 let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
84 Ok((attrs, items, mod_spans))
88 pub(super) type ItemInfo = (Ident, ItemKind);
91 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
92 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
93 self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
98 fn_parse_mode: FnParseMode,
99 force_collect: ForceCollect,
100 ) -> PResult<'a, Option<Item>> {
101 self.recover_diff_marker();
102 let attrs = self.parse_outer_attributes()?;
103 self.recover_diff_marker();
104 self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
107 pub(super) fn parse_item_common(
112 fn_parse_mode: FnParseMode,
113 force_collect: ForceCollect,
114 ) -> PResult<'a, Option<Item>> {
115 // Don't use `maybe_whole` so that we have precise control
116 // over when we bump the parser
117 if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
118 let mut item = item.clone();
121 attrs.prepend_to_nt_inner(&mut item.attrs);
122 return Ok(Some(item.into_inner()));
125 let mut unclosed_delims = vec![];
127 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
129 this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
130 unclosed_delims.append(&mut this.unclosed_delims);
131 Ok((item?, TrailingToken::None))
134 self.unclosed_delims.append(&mut unclosed_delims);
138 fn parse_item_common_(
143 fn_parse_mode: FnParseMode,
144 ) -> PResult<'a, Option<Item>> {
145 let lo = self.token.span;
146 let vis = self.parse_visibility(FollowedByType::No)?;
147 let mut def = self.parse_defaultness();
148 let kind = self.parse_item_kind(
157 if let Some((ident, kind)) = kind {
158 self.error_on_unconsumed_default(def, &kind);
159 let span = lo.to(self.prev_token.span);
160 let id = DUMMY_NODE_ID;
161 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
162 return Ok(Some(item));
165 // At this point, we have failed to parse an item.
166 self.error_on_unmatched_vis(&vis);
167 self.error_on_unmatched_defaultness(def);
169 self.recover_attrs_no_item(&attrs)?;
174 /// Error in-case a non-inherited visibility was parsed but no item followed.
175 fn error_on_unmatched_vis(&self, vis: &Visibility) {
176 if let VisibilityKind::Inherited = vis.kind {
179 let vs = pprust::vis_to_string(&vis);
180 let vs = vs.trim_end();
181 self.struct_span_err(vis.span, &format!("visibility `{vs}` is not followed by an item"))
182 .span_label(vis.span, "the visibility")
183 .help(&format!("you likely meant to define an item, e.g., `{vs} fn foo() {{}}`"))
187 /// Error in-case a `default` was parsed but no item followed.
188 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
189 if let Defaultness::Default(sp) = def {
190 self.struct_span_err(sp, "`default` is not followed by an item")
191 .span_label(sp, "the `default` qualifier")
192 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
197 /// Error in-case `default` was parsed in an in-appropriate context.
198 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
199 if let Defaultness::Default(span) = def {
200 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
201 self.struct_span_err(span, &msg)
202 .span_label(span, "`default` because of this")
203 .note("only associated `fn`, `const`, and `type` items can be `default`")
208 /// Parses one of the items allowed by the flags.
212 macros_allowed: bool,
215 def: &mut Defaultness,
216 fn_parse_mode: FnParseMode,
218 ) -> PResult<'a, Option<ItemInfo>> {
219 let def_final = def == &Defaultness::Final;
220 let mut def_ = || mem::replace(def, Defaultness::Final);
222 let info = if self.eat_keyword_case(kw::Use, case) {
223 self.parse_use_item()?
224 } else if self.check_fn_front_matter(def_final, case) {
226 let (ident, sig, generics, body) =
227 self.parse_fn(attrs, fn_parse_mode, lo, vis, case)?;
228 (ident, ItemKind::Fn(Box::new(Fn { defaultness: def_(), sig, generics, body })))
229 } else if self.eat_keyword(kw::Extern) {
230 if self.eat_keyword(kw::Crate) {
232 self.parse_item_extern_crate()?
235 self.parse_item_foreign_mod(attrs, Unsafe::No)?
237 } else if self.is_unsafe_foreign_mod() {
239 let unsafety = self.parse_unsafety(Case::Sensitive);
240 self.expect_keyword(kw::Extern)?;
241 self.parse_item_foreign_mod(attrs, unsafety)?
242 } else if self.is_static_global() {
244 self.bump(); // `static`
245 let m = self.parse_mutability();
246 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
247 (ident, ItemKind::Static(ty, m, expr))
248 } else if let Const::Yes(const_span) = self.parse_constness(Case::Sensitive) {
250 if self.token.is_keyword(kw::Impl) {
251 // recover from `const impl`, suggest `impl const`
252 self.recover_const_impl(const_span, attrs, def_())?
254 self.recover_const_mut(const_span);
255 let (ident, ty, expr) = self.parse_item_global(None)?;
256 (ident, ItemKind::Const(def_(), ty, expr))
258 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
260 self.parse_item_trait(attrs, lo)?
261 } else if self.check_keyword(kw::Impl)
262 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
265 self.parse_item_impl(attrs, def_())?
266 } else if self.check_keyword(kw::Mod)
267 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
270 self.parse_item_mod(attrs)?
271 } else if self.eat_keyword(kw::Type) {
273 self.parse_type_alias(def_())?
274 } else if self.eat_keyword(kw::Enum) {
276 self.parse_item_enum()?
277 } else if self.eat_keyword(kw::Struct) {
279 self.parse_item_struct()?
280 } else if self.is_kw_followed_by_ident(kw::Union) {
282 self.bump(); // `union`
283 self.parse_item_union()?
284 } else if self.eat_keyword(kw::Macro) {
286 self.parse_item_decl_macro(lo)?
287 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
289 self.parse_item_macro_rules(vis, has_bang)?
290 } else if self.isnt_macro_invocation()
291 && (self.token.is_ident_named(sym::import)
292 || self.token.is_ident_named(sym::using)
293 || self.token.is_ident_named(sym::include)
294 || self.token.is_ident_named(sym::require))
296 return self.recover_import_as_use();
297 } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
298 self.recover_missing_kw_before_item()?;
300 } else if self.isnt_macro_invocation() && case == Case::Sensitive {
303 // Recover wrong cased keywords
304 return self.parse_item_kind(
313 } else if macros_allowed && self.check_path() {
314 // MACRO INVOCATION ITEM
315 (Ident::empty(), ItemKind::MacCall(P(self.parse_item_macro(vis)?)))
322 fn recover_import_as_use(&mut self) -> PResult<'a, Option<(Ident, ItemKind)>> {
323 let span = self.token.span;
324 let token_name = super::token_descr(&self.token);
325 let snapshot = self.create_snapshot_for_diagnostic();
327 match self.parse_use_item() {
329 self.struct_span_err(span, format!("expected item, found {token_name}"))
330 .span_suggestion_short(
332 "items are imported using the `use` keyword",
334 Applicability::MachineApplicable,
341 self.restore_snapshot(snapshot);
347 fn parse_use_item(&mut self) -> PResult<'a, (Ident, ItemKind)> {
348 let tree = self.parse_use_tree()?;
349 if let Err(mut e) = self.expect_semi() {
351 UseTreeKind::Glob => {
352 e.note("the wildcard token must be last on the path");
354 UseTreeKind::Nested(..) => {
355 e.note("glob-like brace syntax must be last on the path");
361 Ok((Ident::empty(), ItemKind::Use(tree)))
364 /// When parsing a statement, would the start of a path be an item?
365 pub(super) fn is_path_start_item(&mut self) -> bool {
366 self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
367 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
368 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
369 || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
372 /// Are we sure this could not possibly be a macro invocation?
373 fn isnt_macro_invocation(&mut self) -> bool {
374 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
377 /// Recover on encountering a struct or method definition where the user
378 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
379 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
380 // Space between `pub` keyword and the identifier
383 // ^^^ `sp` points here
384 let sp = self.prev_token.span.between(self.token.span);
385 let full_sp = self.prev_token.span.to(self.token.span);
386 let ident_sp = self.token.span;
387 if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace)) {
388 // possible public struct definition where `struct` was forgotten
389 let ident = self.parse_ident().unwrap();
390 let msg = format!("add `struct` here to parse `{ident}` as a public struct");
391 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
392 err.span_suggestion_short(
396 Applicability::MaybeIncorrect, // speculative
399 } else if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Parenthesis)) {
400 let ident = self.parse_ident().unwrap();
402 let kw_name = self.recover_first_param();
403 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::Yes);
404 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
405 self.eat_to_tokens(&[&token::OpenDelim(Delimiter::Brace)]);
407 ("fn", kw_name, false)
408 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
410 ("fn", kw_name, false)
411 } else if self.check(&token::Colon) {
415 ("fn` or `struct", "function or struct", true)
418 let msg = format!("missing `{kw}` for {kw_name} definition");
419 let mut err = self.struct_span_err(sp, &msg);
421 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
423 format!("add `{kw}` here to parse `{ident}` as a public {kw_name}");
424 err.span_suggestion_short(
428 Applicability::MachineApplicable,
430 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
433 "if you meant to call a macro, try",
434 format!("{}!", snippet),
435 // this is the `ambiguous` conditional branch
436 Applicability::MaybeIncorrect,
440 "if you meant to call a macro, remove the `pub` \
441 and add a trailing `!` after the identifier",
445 } else if self.look_ahead(1, |t| *t == token::Lt) {
446 let ident = self.parse_ident().unwrap();
447 self.eat_to_tokens(&[&token::Gt]);
449 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(Delimiter::Parenthesis)) {
450 ("fn", self.recover_first_param(), false)
451 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
452 ("struct", "struct", false)
454 ("fn` or `struct", "function or struct", true)
456 let msg = format!("missing `{kw}` for {kw_name} definition");
457 let mut err = self.struct_span_err(sp, &msg);
459 err.span_suggestion_short(
461 &format!("add `{kw}` here to parse `{ident}` as a public {kw_name}"),
463 Applicability::MachineApplicable,
472 /// Parses an item macro, e.g., `item!();`.
473 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
474 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
475 self.expect(&token::Not)?; // `!`
476 match self.parse_delim_args() {
477 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
479 self.eat_semi_for_macro_if_needed(&args);
480 self.complain_if_pub_macro(vis, false);
481 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
485 // Maybe the user misspelled `macro_rules` (issue #91227)
486 if self.token.is_ident()
487 && path.segments.len() == 1
488 && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
492 "perhaps you meant to define a macro",
494 Applicability::MachineApplicable,
502 /// Recover if we parsed attributes and expected an item but there was none.
503 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
504 let ([start @ end] | [start, .., end]) = attrs else {
507 let msg = if end.is_doc_comment() {
508 "expected item after doc comment"
510 "expected item after attributes"
512 let mut err = self.struct_span_err(end.span, msg);
513 if end.is_doc_comment() {
514 err.span_label(end.span, "this doc comment doesn't document anything");
516 if end.meta_kind().is_some() {
517 if self.token.kind == TokenKind::Semi {
518 err.span_suggestion_verbose(
520 "consider removing this semicolon",
522 Applicability::MaybeIncorrect,
526 if let [.., penultimate, _] = attrs {
527 err.span_label(start.span.to(penultimate.span), "other attributes here");
532 fn is_async_fn(&self) -> bool {
533 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
536 fn parse_polarity(&mut self) -> ast::ImplPolarity {
537 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
538 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
540 ast::ImplPolarity::Negative(self.prev_token.span)
542 ast::ImplPolarity::Positive
546 /// Parses an implementation item.
548 /// ```ignore (illustrative)
549 /// impl<'a, T> TYPE { /* impl items */ }
550 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
551 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
552 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
555 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
557 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
558 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
563 defaultness: Defaultness,
564 ) -> PResult<'a, ItemInfo> {
565 let unsafety = self.parse_unsafety(Case::Sensitive);
566 self.expect_keyword(kw::Impl)?;
568 // First, parse generic parameters if necessary.
569 let mut generics = if self.choose_generics_over_qpath(0) {
570 self.parse_generics()?
572 let mut generics = Generics::default();
574 // /\ this is where `generics.span` should point when there are no type params.
575 generics.span = self.prev_token.span.shrink_to_hi();
579 let constness = self.parse_constness(Case::Sensitive);
580 if let Const::Yes(span) = constness {
581 self.sess.gated_spans.gate(sym::const_trait_impl, span);
584 let polarity = self.parse_polarity();
586 // Parse both types and traits as a type, then reinterpret if necessary.
587 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
588 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
590 let span = self.prev_token.span.between(self.token.span);
591 self.struct_span_err(span, "missing trait in a trait impl")
596 Applicability::HasPlaceholders,
599 span.to(self.token.span),
600 "for an inherent impl, drop this `for`",
602 Applicability::MaybeIncorrect,
606 kind: TyKind::Path(None, err_path(span)),
612 self.parse_ty_with_generics_recovery(&generics)?
615 // If `for` is missing we try to recover.
616 let has_for = self.eat_keyword(kw::For);
617 let missing_for_span = self.prev_token.span.between(self.token.span);
619 let ty_second = if self.token == token::DotDot {
620 // We need to report this error after `cfg` expansion for compatibility reasons
621 self.bump(); // `..`, do not add it to expected tokens
622 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
623 } else if has_for || self.token.can_begin_type() {
624 Some(self.parse_ty()?)
629 generics.where_clause = self.parse_where_clause()?;
631 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
633 let item_kind = match ty_second {
635 // impl Trait for Type
637 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
638 .span_suggestion_short(
642 Applicability::MachineApplicable,
647 let ty_first = ty_first.into_inner();
648 let path = match ty_first.kind {
649 // This notably includes paths passed through `ty` macro fragments (#46438).
650 TyKind::Path(None, path) => path,
652 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
653 err_path(ty_first.span)
656 let trait_ref = TraitRef { path, ref_id: ty_first.id };
658 ItemKind::Impl(Box::new(Impl {
664 of_trait: Some(trait_ref),
671 ItemKind::Impl(Box::new(Impl {
684 Ok((Ident::empty(), item_kind))
687 fn parse_item_list<T>(
690 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
691 ) -> PResult<'a, Vec<T>> {
692 let open_brace_span = self.token.span;
694 // Recover `impl Ty;` instead of `impl Ty {}`
695 if self.token == TokenKind::Semi {
696 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
701 self.expect(&token::OpenDelim(Delimiter::Brace))?;
702 attrs.extend(self.parse_inner_attributes()?);
704 let mut items = Vec::new();
705 while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
706 if self.recover_doc_comment_before_brace() {
709 self.recover_diff_marker();
710 match parse_item(self) {
712 let mut is_unnecessary_semicolon = !items.is_empty()
713 // When the close delim is `)` in a case like the following, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
714 // but the actual `token.kind` is `token::CloseDelim(Delimiter::Brace)`.
715 // This is because the `token.kind` of the close delim is treated as the same as
716 // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
717 // Therefore, `token.kind` should not be compared here.
722 // fn qux() -> Option<usize> {
725 // ^ this close delim
730 .span_to_snippet(self.prev_token.span)
731 .map_or(false, |snippet| snippet == "}")
732 && self.token.kind == token::Semi;
733 let mut semicolon_span = self.token.span;
734 if !is_unnecessary_semicolon {
735 // #105369, Detect spurious `;` before assoc fn body
736 is_unnecessary_semicolon = self.token == token::OpenDelim(Delimiter::Brace)
737 && self.prev_token.kind == token::Semi;
738 semicolon_span = self.prev_token.span;
740 // We have to bail or we'll potentially never make progress.
741 let non_item_span = self.token.span;
742 let is_let = self.token.is_keyword(kw::Let);
744 let mut err = self.struct_span_err(non_item_span, "non-item in item list");
745 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
749 "consider using `const` instead of `let` for associated const",
751 Applicability::MachineApplicable,
754 err.span_label(open_brace_span, "item list starts here")
755 .span_label(non_item_span, "non-item starts here")
756 .span_label(self.prev_token.span, "item list ends here");
758 if is_unnecessary_semicolon {
761 "consider removing this semicolon",
763 Applicability::MaybeIncorrect,
769 Ok(Some(item)) => items.extend(item),
771 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
772 err.span_label(open_brace_span, "while parsing this item list starting here")
773 .span_label(self.prev_token.span, "the item list ends here")
782 /// Recover on a doc comment before `}`.
783 fn recover_doc_comment_before_brace(&mut self) -> bool {
784 if let token::DocComment(..) = self.token.kind {
785 if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
790 "found a documentation comment that doesn't document anything",
792 .span_label(self.token.span, "this doc comment doesn't document anything")
794 "doc comments must come before what they document, if a comment was \
805 /// Parses defaultness (i.e., `default` or nothing).
806 fn parse_defaultness(&mut self) -> Defaultness {
807 // We are interested in `default` followed by another identifier.
808 // However, we must avoid keywords that occur as binary operators.
809 // Currently, the only applicable keyword is `as` (`default as Ty`).
810 if self.check_keyword(kw::Default)
811 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
813 self.bump(); // `default`
814 Defaultness::Default(self.prev_token.uninterpolated_span())
820 /// Is this an `(unsafe auto? | auto) trait` item?
821 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
823 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
825 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
828 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
829 fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
830 let unsafety = self.parse_unsafety(Case::Sensitive);
831 // Parse optional `auto` prefix.
832 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
834 self.expect_keyword(kw::Trait)?;
835 let ident = self.parse_ident()?;
836 let mut generics = self.parse_generics()?;
838 // Parse optional colon and supertrait bounds.
839 let had_colon = self.eat(&token::Colon);
840 let span_at_colon = self.prev_token.span;
841 let bounds = if had_colon {
842 self.parse_generic_bounds(Some(self.prev_token.span))?
847 let span_before_eq = self.prev_token.span;
848 if self.eat(&token::Eq) {
849 // It's a trait alias.
851 let span = span_at_colon.to(span_before_eq);
852 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
855 let bounds = self.parse_generic_bounds(None)?;
856 generics.where_clause = self.parse_where_clause()?;
859 let whole_span = lo.to(self.prev_token.span);
860 if is_auto == IsAuto::Yes {
861 let msg = "trait aliases cannot be `auto`";
862 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
864 if let Unsafe::Yes(_) = unsafety {
865 let msg = "trait aliases cannot be `unsafe`";
866 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
869 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
871 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
873 // It's a normal trait.
874 generics.where_clause = self.parse_where_clause()?;
875 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
878 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
883 pub fn parse_impl_item(
885 force_collect: ForceCollect,
886 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
887 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
888 self.parse_assoc_item(fn_parse_mode, force_collect)
891 pub fn parse_trait_item(
893 force_collect: ForceCollect,
894 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
896 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
897 self.parse_assoc_item(fn_parse_mode, force_collect)
900 /// Parses associated items.
903 fn_parse_mode: FnParseMode,
904 force_collect: ForceCollect,
905 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
906 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
907 |Item { attrs, id, span, vis, ident, kind, tokens }| {
908 let kind = match AssocItemKind::try_from(kind) {
910 Err(kind) => match kind {
911 ItemKind::Static(a, _, b) => {
912 self.struct_span_err(span, "associated `static` items are not allowed")
914 AssocItemKind::Const(Defaultness::Final, a, b)
916 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
919 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
924 /// Parses a `type` alias with the following grammar:
926 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
928 /// The `"type"` has already been eaten.
929 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
930 let ident = self.parse_ident()?;
931 let mut generics = self.parse_generics()?;
933 // Parse optional colon and param bounds.
935 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
936 let before_where_clause = self.parse_where_clause()?;
938 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
940 let after_where_clause = self.parse_where_clause()?;
942 let where_clauses = (
943 TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
944 TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
946 let where_predicates_split = before_where_clause.predicates.len();
947 let mut predicates = before_where_clause.predicates;
948 predicates.extend(after_where_clause.predicates.into_iter());
949 let where_clause = WhereClause {
950 has_where_token: before_where_clause.has_where_token
951 || after_where_clause.has_where_token,
955 generics.where_clause = where_clause;
961 ItemKind::TyAlias(Box::new(TyAlias {
965 where_predicates_split,
972 /// Parses a `UseTree`.
975 /// USE_TREE = [`::`] `*` |
976 /// [`::`] `{` USE_TREE_LIST `}` |
978 /// PATH `::` `{` USE_TREE_LIST `}` |
979 /// PATH [`as` IDENT]
981 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
982 let lo = self.token.span;
985 ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo(), tokens: None };
986 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
987 || self.check(&token::BinOp(token::Star))
988 || self.is_import_coupler()
990 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
991 let mod_sep_ctxt = self.token.span.ctxt();
992 if self.eat(&token::ModSep) {
995 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
998 self.parse_use_tree_glob_or_nested()?
1000 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
1001 prefix = self.parse_path(PathStyle::Mod)?;
1003 if self.eat(&token::ModSep) {
1004 self.parse_use_tree_glob_or_nested()?
1006 // Recover from using a colon as path separator.
1007 while self.eat_noexpect(&token::Colon) {
1008 self.struct_span_err(self.prev_token.span, "expected `::`, found `:`")
1009 .span_suggestion_short(
1010 self.prev_token.span,
1013 Applicability::MachineApplicable,
1015 .note_once("import paths are delimited using `::`")
1018 // We parse the rest of the path and append it to the original prefix.
1019 self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1020 prefix.span = lo.to(self.prev_token.span);
1023 UseTreeKind::Simple(self.parse_rename()?)
1027 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
1030 /// Parses `*` or `{...}`.
1031 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1032 Ok(if self.eat(&token::BinOp(token::Star)) {
1035 UseTreeKind::Nested(self.parse_use_tree_list()?)
1039 /// Parses a `UseTreeKind::Nested(list)`.
1042 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
1044 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1045 self.parse_delim_comma_seq(Delimiter::Brace, |p| {
1046 p.recover_diff_marker();
1047 Ok((p.parse_use_tree()?, DUMMY_NODE_ID))
1052 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1053 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1056 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1057 match self.token.ident() {
1058 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1062 _ => self.parse_ident(),
1066 /// Parses `extern crate` links.
1070 /// ```ignore (illustrative)
1071 /// extern crate foo;
1072 /// extern crate bar as foo;
1074 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1075 // Accept `extern crate name-like-this` for better diagnostics
1076 let orig_name = self.parse_crate_name_with_dashes()?;
1077 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1078 (rename, Some(orig_name.name))
1082 self.expect_semi()?;
1083 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1086 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1087 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1088 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1090 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1091 self.parse_path_segment_ident()
1095 let mut idents = vec![];
1096 let mut replacement = vec![];
1097 let mut fixed_crate_name = false;
1098 // Accept `extern crate name-like-this` for better diagnostics.
1099 let dash = token::BinOp(token::BinOpToken::Minus);
1100 if self.token == dash {
1101 // Do not include `-` as part of the expected tokens list.
1102 while self.eat(&dash) {
1103 fixed_crate_name = true;
1104 replacement.push((self.prev_token.span, "_".to_string()));
1105 idents.push(self.parse_ident()?);
1108 if fixed_crate_name {
1109 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1110 let mut fixed_name = ident.name.to_string();
1111 for part in idents {
1112 fixed_name.push_str(&format!("_{}", part.name));
1114 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1116 self.struct_span_err(fixed_name_sp, error_msg)
1117 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1118 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1124 /// Parses `extern` for foreign ABIs modules.
1126 /// `extern` is expected to have been consumed before calling this method.
1130 /// ```ignore (only-for-syntax-highlight)
1134 fn parse_item_foreign_mod(
1136 attrs: &mut AttrVec,
1137 mut unsafety: Unsafe,
1138 ) -> PResult<'a, ItemInfo> {
1139 let abi = self.parse_abi(); // ABI?
1140 if unsafety == Unsafe::No
1141 && self.token.is_keyword(kw::Unsafe)
1142 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1144 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1146 unsafety = Unsafe::Yes(self.token.span);
1147 self.eat_keyword(kw::Unsafe);
1149 let module = ast::ForeignMod {
1152 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1154 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1157 /// Parses a foreign item (one in an `extern { ... }` block).
1158 pub fn parse_foreign_item(
1160 force_collect: ForceCollect,
1161 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1162 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1163 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1164 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1165 let kind = match ForeignItemKind::try_from(kind) {
1167 Err(kind) => match kind {
1168 ItemKind::Const(_, a, b) => {
1169 self.error_on_foreign_const(span, ident);
1170 ForeignItemKind::Static(a, Mutability::Not, b)
1172 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1175 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1180 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1181 let span = self.sess.source_map().guess_head_span(span);
1182 let descr = kind.descr();
1183 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1184 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1189 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1190 self.struct_span_err(ident.span, "extern items cannot be `const`")
1192 span.with_hi(ident.span.lo()),
1193 "try using a static value",
1195 Applicability::MachineApplicable,
1197 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1201 fn is_unsafe_foreign_mod(&self) -> bool {
1202 self.token.is_keyword(kw::Unsafe)
1203 && self.is_keyword_ahead(1, &[kw::Extern])
1205 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1206 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1210 fn is_static_global(&mut self) -> bool {
1211 if self.check_keyword(kw::Static) {
1212 // Check if this could be a closure.
1213 !self.look_ahead(1, |token| {
1214 if token.is_keyword(kw::Move) {
1217 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1224 /// Recover on `const mut` with `const` already eaten.
1225 fn recover_const_mut(&mut self, const_span: Span) {
1226 if self.eat_keyword(kw::Mut) {
1227 let span = self.prev_token.span;
1228 self.struct_span_err(span, "const globals cannot be mutable")
1229 .span_label(span, "cannot be mutable")
1232 "you might want to declare a static instead",
1234 Applicability::MaybeIncorrect,
1237 } else if self.eat_keyword(kw::Let) {
1238 let span = self.prev_token.span;
1239 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1241 const_span.to(span),
1244 Applicability::MaybeIncorrect,
1250 /// Recover on `const impl` with `const` already eaten.
1251 fn recover_const_impl(
1254 attrs: &mut AttrVec,
1255 defaultness: Defaultness,
1256 ) -> PResult<'a, ItemInfo> {
1257 let impl_span = self.token.span;
1258 let mut err = self.expected_ident_found();
1260 // Only try to recover if this is implementing a trait for a type
1261 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1262 Ok(impl_info) => impl_info,
1263 Err(recovery_error) => {
1264 // Recovery failed, raise the "expected identifier" error
1265 recovery_error.cancel();
1270 match &mut impl_info.1 {
1271 ItemKind::Impl(box Impl { of_trait: Some(trai), constness, .. }) => {
1272 *constness = Const::Yes(const_span);
1274 let before_trait = trai.path.span.shrink_to_lo();
1275 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1276 err.multipart_suggestion(
1277 "you might have meant to write a const trait impl",
1278 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1279 Applicability::MaybeIncorrect,
1283 ItemKind::Impl { .. } => return Err(err),
1284 _ => unreachable!(),
1290 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1291 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1293 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1294 fn parse_item_global(
1296 m: Option<Mutability>,
1297 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1298 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1300 // Parse the type of a `const` or `static mut?` item.
1301 // That is, the `":" $ty` fragment.
1302 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1304 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1305 (true, false) => self.parse_ty()?,
1306 (colon, _) => self.recover_missing_const_type(colon, m),
1309 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1310 self.expect_semi()?;
1314 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1315 /// This means that the type is missing.
1316 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1317 // Construct the error and stash it away with the hope
1318 // that typeck will later enrich the error with a type.
1319 let kind = match m {
1320 Some(Mutability::Mut) => "static mut",
1321 Some(Mutability::Not) => "static",
1325 let colon = match colon_present {
1330 let span = self.prev_token.span.shrink_to_hi();
1331 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1332 err.span_suggestion(
1334 "provide a type for the item",
1335 format!("{colon} <type>"),
1336 Applicability::HasPlaceholders,
1338 err.stash(span, StashKey::ItemNoType);
1340 // The user intended that the type be inferred,
1341 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1342 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1345 /// Parses an enum declaration.
1346 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1347 if self.token.is_keyword(kw::Struct) {
1348 let span = self.prev_token.span.to(self.token.span);
1349 let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1350 err.span_suggestion(
1352 "replace `enum struct` with",
1354 Applicability::MachineApplicable,
1356 if self.look_ahead(1, |t| t.is_ident()) {
1364 let id = self.parse_ident()?;
1365 let mut generics = self.parse_generics()?;
1366 generics.where_clause = self.parse_where_clause()?;
1368 // Possibly recover `enum Foo;` instead of `enum Foo {}`
1369 let (variants, _) = if self.token == TokenKind::Semi {
1370 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1374 self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1376 e.span_label(id.span, "while parsing this enum");
1377 self.recover_stmt();
1383 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1384 Ok((id, ItemKind::Enum(enum_definition, generics)))
1387 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1388 self.recover_diff_marker();
1389 let variant_attrs = self.parse_outer_attributes()?;
1390 self.recover_diff_marker();
1391 self.collect_tokens_trailing_token(
1394 |this, variant_attrs| {
1395 let vlo = this.token.span;
1397 let vis = this.parse_visibility(FollowedByType::No)?;
1398 if !this.recover_nested_adt_item(kw::Enum)? {
1399 return Ok((None, TrailingToken::None));
1401 let ident = this.parse_field_ident("enum", vlo)?;
1403 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1404 // Parse a struct variant.
1405 let (fields, recovered) =
1406 this.parse_record_struct_body("struct", ident.span, false)?;
1407 VariantData::Struct(fields, recovered)
1408 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1409 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1411 VariantData::Unit(DUMMY_NODE_ID)
1415 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1417 let vr = ast::Variant {
1421 attrs: variant_attrs,
1424 span: vlo.to(this.prev_token.span),
1425 is_placeholder: false,
1428 Ok((Some(vr), TrailingToken::MaybeComma))
1430 ).map_err(|mut err|{
1431 err.help("enum variants can be `Variant`, `Variant = <integer>`, `Variant(Type, ..., TypeN)` or `Variant { fields: Types }`");
1436 /// Parses `struct Foo { ... }`.
1437 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1438 let class_name = self.parse_ident()?;
1440 let mut generics = self.parse_generics()?;
1442 // There is a special case worth noting here, as reported in issue #17904.
1443 // If we are parsing a tuple struct it is the case that the where clause
1444 // should follow the field list. Like so:
1446 // struct Foo<T>(T) where T: Copy;
1448 // If we are parsing a normal record-style struct it is the case
1449 // that the where clause comes before the body, and after the generics.
1450 // So if we look ahead and see a brace or a where-clause we begin
1451 // parsing a record style struct.
1453 // Otherwise if we look ahead and see a paren we parse a tuple-style
1456 let vdata = if self.token.is_keyword(kw::Where) {
1457 let tuple_struct_body;
1458 (generics.where_clause, tuple_struct_body) =
1459 self.parse_struct_where_clause(class_name, generics.span)?;
1461 if let Some(body) = tuple_struct_body {
1462 // If we see a misplaced tuple struct body: `struct Foo<T> where T: Copy, (T);`
1463 let body = VariantData::Tuple(body, DUMMY_NODE_ID);
1464 self.expect_semi()?;
1466 } else if self.eat(&token::Semi) {
1467 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1468 VariantData::Unit(DUMMY_NODE_ID)
1470 // If we see: `struct Foo<T> where T: Copy { ... }`
1471 let (fields, recovered) = self.parse_record_struct_body(
1474 generics.where_clause.has_where_token,
1476 VariantData::Struct(fields, recovered)
1478 // No `where` so: `struct Foo<T>;`
1479 } else if self.eat(&token::Semi) {
1480 VariantData::Unit(DUMMY_NODE_ID)
1481 // Record-style struct definition
1482 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1483 let (fields, recovered) = self.parse_record_struct_body(
1486 generics.where_clause.has_where_token,
1488 VariantData::Struct(fields, recovered)
1489 // Tuple-style struct definition with optional where-clause.
1490 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1491 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1492 generics.where_clause = self.parse_where_clause()?;
1493 self.expect_semi()?;
1496 let token_str = super::token_descr(&self.token);
1498 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1500 let mut err = self.struct_span_err(self.token.span, msg);
1501 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1505 Ok((class_name, ItemKind::Struct(vdata, generics)))
1508 /// Parses `union Foo { ... }`.
1509 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1510 let class_name = self.parse_ident()?;
1512 let mut generics = self.parse_generics()?;
1514 let vdata = if self.token.is_keyword(kw::Where) {
1515 generics.where_clause = self.parse_where_clause()?;
1516 let (fields, recovered) = self.parse_record_struct_body(
1519 generics.where_clause.has_where_token,
1521 VariantData::Struct(fields, recovered)
1522 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1523 let (fields, recovered) = self.parse_record_struct_body(
1526 generics.where_clause.has_where_token,
1528 VariantData::Struct(fields, recovered)
1530 let token_str = super::token_descr(&self.token);
1531 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1532 let mut err = self.struct_span_err(self.token.span, msg);
1533 err.span_label(self.token.span, "expected `where` or `{` after union name");
1537 Ok((class_name, ItemKind::Union(vdata, generics)))
1540 fn parse_record_struct_body(
1545 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1546 let mut fields = Vec::new();
1547 let mut recovered = false;
1548 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1549 while self.token != token::CloseDelim(Delimiter::Brace) {
1550 let field = self.parse_field_def(adt_ty).map_err(|e| {
1551 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1556 Ok(field) => fields.push(field),
1558 err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1564 self.eat(&token::CloseDelim(Delimiter::Brace));
1566 let token_str = super::token_descr(&self.token);
1568 "expected {}`{{` after struct name, found {}",
1569 if parsed_where { "" } else { "`where`, or " },
1572 let mut err = self.struct_span_err(self.token.span, msg);
1576 "expected {}`{{` after struct name",
1577 if parsed_where { "" } else { "`where`, or " }
1583 Ok((fields, recovered))
1586 pub(super) fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1587 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1588 // Unit like structs are handled in parse_item_struct function
1589 self.parse_paren_comma_seq(|p| {
1590 let attrs = p.parse_outer_attributes()?;
1591 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1592 let mut snapshot = None;
1593 if p.is_diff_marker(&TokenKind::BinOp(token::Shl), &TokenKind::Lt) {
1594 // Account for `<<<<<<<` diff markers. We can't proactively error here because
1595 // that can be a valid type start, so we snapshot and reparse only we've
1596 // encountered another parse error.
1597 snapshot = Some(p.create_snapshot_for_diagnostic());
1599 let lo = p.token.span;
1600 let vis = match p.parse_visibility(FollowedByType::Yes) {
1603 if let Some(ref mut snapshot) = snapshot {
1604 snapshot.recover_diff_marker();
1609 let ty = match p.parse_ty() {
1612 if let Some(ref mut snapshot) = snapshot {
1613 snapshot.recover_diff_marker();
1621 span: lo.to(ty.span),
1627 is_placeholder: false,
1629 TrailingToken::MaybeComma,
1636 /// Parses an element of a struct declaration.
1637 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1638 self.recover_diff_marker();
1639 let attrs = self.parse_outer_attributes()?;
1640 self.recover_diff_marker();
1641 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1642 let lo = this.token.span;
1643 let vis = this.parse_visibility(FollowedByType::No)?;
1644 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1648 /// Parses a structure field declaration.
1649 fn parse_single_struct_field(
1655 ) -> PResult<'a, FieldDef> {
1656 let mut seen_comma: bool = false;
1657 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1658 if self.token == token::Comma {
1661 if self.eat(&token::Semi) {
1662 let sp = self.prev_token.span;
1663 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1664 err.span_suggestion_short(
1666 "replace `;` with `,`",
1668 Applicability::MachineApplicable,
1672 match self.token.kind {
1676 token::CloseDelim(Delimiter::Brace) => {}
1677 token::DocComment(..) => {
1678 let previous_span = self.prev_token.span;
1679 let mut err = DocCommentDoesNotDocumentAnything {
1680 span: self.token.span,
1681 missing_comma: None,
1683 self.bump(); // consume the doc comment
1684 let comma_after_doc_seen = self.eat(&token::Comma);
1685 // `seen_comma` is always false, because we are inside doc block
1686 // condition is here to make code more readable
1687 if !seen_comma && comma_after_doc_seen {
1690 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1691 self.sess.emit_err(err);
1694 let sp = previous_span.shrink_to_hi();
1695 err.missing_comma = Some(sp);
1697 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1701 let sp = self.prev_token.span.shrink_to_hi();
1702 let mut err = self.struct_span_err(
1704 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1707 // Try to recover extra trailing angle brackets
1708 let mut recovered = false;
1709 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1710 if let Some(last_segment) = segments.last() {
1711 recovered = self.check_trailing_angle_brackets(
1713 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1716 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1718 self.eat(&token::Comma);
1719 // `check_trailing_angle_brackets` already emitted a nicer error
1720 // NOTE(eddyb) this was `.cancel()`, but `err`
1721 // gets returned, so we can't fully defuse it.
1727 if self.token.is_ident()
1728 || (self.token.kind == TokenKind::Pound
1729 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1731 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1732 // emit the diagnostic and keep going
1733 err.span_suggestion(
1735 "try adding a comma",
1737 Applicability::MachineApplicable,
1744 // Make sure an error was emitted (either by recovering an angle bracket,
1745 // or by finding an identifier as the next token), since we're
1746 // going to continue parsing
1747 assert!(self.sess.span_diagnostic.has_errors().is_some());
1756 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1757 if let Err(mut err) = self.expect(&token::Colon) {
1758 let sm = self.sess.source_map();
1759 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1760 let semi_typo = self.token.kind == token::Semi
1761 && self.look_ahead(1, |t| {
1763 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1764 // when there's no type and `;` was used instead of a comma.
1765 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1766 (Ok(l), Ok(r)) => l.line == r.line,
1770 if eq_typo || semi_typo {
1772 // Gracefully handle small typos.
1773 err.span_suggestion_short(
1774 self.prev_token.span,
1775 "field names and their types are separated with `:`",
1777 Applicability::MachineApplicable,
1787 /// Parses a structure field.
1788 fn parse_name_and_ty(
1794 ) -> PResult<'a, FieldDef> {
1795 let name = self.parse_field_ident(adt_ty, lo)?;
1796 self.expect_field_ty_separator()?;
1797 let ty = self.parse_ty()?;
1798 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1799 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1800 .span_suggestion_verbose(
1802 "write a path separator here",
1804 Applicability::MaybeIncorrect,
1808 if self.token.kind == token::Eq {
1810 let const_expr = self.parse_anon_const_expr()?;
1811 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1812 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1815 "remove this unsupported default value",
1817 Applicability::MachineApplicable,
1822 span: lo.to(self.prev_token.span),
1828 is_placeholder: false,
1832 /// Parses a field identifier. Specialized version of `parse_ident_common`
1833 /// for better diagnostics and suggestions.
1834 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1835 let (ident, is_raw) = self.ident_or_err()?;
1836 if !is_raw && ident.is_reserved() {
1837 let snapshot = self.create_snapshot_for_diagnostic();
1838 let err = if self.check_fn_front_matter(false, Case::Sensitive) {
1839 let inherited_vis = Visibility {
1840 span: rustc_span::DUMMY_SP,
1841 kind: VisibilityKind::Inherited,
1844 // We use `parse_fn` to get a span for the function
1845 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1846 match self.parse_fn(
1847 &mut AttrVec::new(),
1854 let mut err = self.struct_span_err(
1855 lo.to(self.prev_token.span),
1856 &format!("functions are not allowed in {adt_ty} definitions"),
1859 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1861 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1866 self.restore_snapshot(snapshot);
1867 self.expected_ident_found()
1870 } else if self.eat_keyword(kw::Struct) {
1871 match self.parse_item_struct() {
1873 let mut err = self.struct_span_err(
1874 lo.with_hi(ident.span.hi()),
1875 &format!("structs are not allowed in {adt_ty} definitions"),
1877 err.help("consider creating a new `struct` definition instead of nesting");
1882 self.restore_snapshot(snapshot);
1883 self.expected_ident_found()
1887 let mut err = self.expected_ident_found();
1888 if self.eat_keyword_noexpect(kw::Let)
1889 && let removal_span = self.prev_token.span.until(self.token.span)
1890 && let Ok(ident) = self.parse_ident_common(false)
1891 // Cancel this error, we don't need it.
1892 .map_err(|err| err.cancel())
1893 && self.token.kind == TokenKind::Colon
1895 err.span_suggestion(
1897 "remove this `let` keyword",
1899 Applicability::MachineApplicable,
1901 err.note("the `let` keyword is not allowed in `struct` fields");
1902 err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1906 self.restore_snapshot(snapshot);
1916 /// Parses a declarative macro 2.0 definition.
1917 /// The `macro` keyword has already been parsed.
1919 /// MacBody = "{" TOKEN_STREAM "}" ;
1920 /// MacParams = "(" TOKEN_STREAM ")" ;
1921 /// DeclMac = "macro" Ident MacParams? MacBody ;
1923 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1924 let ident = self.parse_ident()?;
1925 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1926 self.parse_delim_args()? // `MacBody`
1927 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1928 let params = self.parse_token_tree(); // `MacParams`
1929 let pspan = params.span();
1930 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1931 return self.unexpected();
1933 let body = self.parse_token_tree(); // `MacBody`
1934 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1935 let bspan = body.span();
1936 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1937 let tokens = TokenStream::new(vec![params, arrow, body]);
1938 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1939 P(DelimArgs { dspan, delim: MacDelimiter::Brace, tokens })
1941 return self.unexpected();
1944 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1945 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1948 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1949 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1950 if self.check_keyword(kw::MacroRules) {
1951 let macro_rules_span = self.token.span;
1953 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1954 return IsMacroRulesItem::Yes { has_bang: true };
1955 } else if self.look_ahead(1, |t| (t.is_ident())) {
1957 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1962 Applicability::MachineApplicable,
1966 return IsMacroRulesItem::Yes { has_bang: false };
1970 IsMacroRulesItem::No
1973 /// Parses a `macro_rules! foo { ... }` declarative macro.
1974 fn parse_item_macro_rules(
1978 ) -> PResult<'a, ItemInfo> {
1979 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1982 self.expect(&token::Not)?; // `!`
1984 let ident = self.parse_ident()?;
1986 if self.eat(&token::Not) {
1987 // Handle macro_rules! foo!
1988 let span = self.prev_token.span;
1989 self.struct_span_err(span, "macro names aren't followed by a `!`")
1990 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1994 let body = self.parse_delim_args()?;
1995 self.eat_semi_for_macro_if_needed(&body);
1996 self.complain_if_pub_macro(vis, true);
1998 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
2001 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
2002 /// If that's not the case, emit an error.
2003 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
2004 if let VisibilityKind::Inherited = vis.kind {
2008 let vstr = pprust::vis_to_string(vis);
2009 let vstr = vstr.trim_end();
2011 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
2012 self.struct_span_err(vis.span, &msg)
2015 "try exporting the macro",
2017 Applicability::MaybeIncorrect, // speculative
2021 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
2024 "remove the visibility",
2026 Applicability::MachineApplicable,
2028 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
2033 fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs) {
2034 if args.need_semicolon() && !self.eat(&token::Semi) {
2035 self.report_invalid_macro_expansion_item(args);
2039 fn report_invalid_macro_expansion_item(&self, args: &DelimArgs) {
2040 let span = args.dspan.entire();
2041 let mut err = self.struct_span_err(
2043 "macros that expand to items must be delimited with braces or followed by a semicolon",
2045 // FIXME: This will make us not emit the help even for declarative
2046 // macros within the same crate (that we can fix), which is sad.
2047 if !span.from_expansion() {
2048 if self.unclosed_delims.is_empty() {
2049 let DelimSpan { open, close } = args.dspan;
2050 err.multipart_suggestion(
2051 "change the delimiters to curly braces",
2052 vec![(open, "{".to_string()), (close, '}'.to_string())],
2053 Applicability::MaybeIncorrect,
2056 err.span_suggestion(
2058 "change the delimiters to curly braces",
2060 Applicability::HasPlaceholders,
2063 err.span_suggestion(
2064 span.shrink_to_hi(),
2067 Applicability::MaybeIncorrect,
2073 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2074 /// it is, we try to parse the item and report error about nested types.
2075 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2076 if (self.token.is_keyword(kw::Enum)
2077 || self.token.is_keyword(kw::Struct)
2078 || self.token.is_keyword(kw::Union))
2079 && self.look_ahead(1, |t| t.is_ident())
2081 let kw_token = self.token.clone();
2082 let kw_str = pprust::token_to_string(&kw_token);
2083 let item = self.parse_item(ForceCollect::No)?;
2085 self.struct_span_err(
2087 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
2091 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2093 Applicability::MaybeIncorrect,
2096 // We successfully parsed the item but we must inform the caller about nested problem.
2103 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2105 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2107 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2108 /// were allowed to omit parameter names. In 2018, they became required.
2109 type ReqName = fn(Edition) -> bool;
2111 /// Parsing configuration for functions.
2113 /// The syntax of function items is slightly different within trait definitions,
2114 /// impl blocks, and modules. It is still parsed using the same code, just with
2115 /// different flags set, so that even when the input is wrong and produces a parse
2116 /// error, it still gets into the AST and the rest of the parser and
2117 /// type checker can run.
2118 #[derive(Clone, Copy)]
2119 pub(crate) struct FnParseMode {
2120 /// A function pointer that decides if, per-parameter `p`, `p` must have a
2121 /// pattern or just a type. This field affects parsing of the parameters list.
2124 /// fn foo(alef: A) -> X { X::new() }
2125 /// -----^^ affects parsing this part of the function signature
2127 /// if req_name returns false, then this name is optional
2132 /// if req_name returns true, this is an error
2135 /// Calling this function pointer should only return false if:
2137 /// * The item is being parsed inside of a trait definition.
2138 /// Within an impl block or a module, it should always evaluate
2140 /// * The span is from Edition 2015. In particular, you can get a
2141 /// 2015 span inside a 2021 crate using macros.
2142 pub req_name: ReqName,
2143 /// If this flag is set to `true`, then plain, semicolon-terminated function
2144 /// prototypes are not allowed here.
2147 /// fn foo(alef: A) -> X { X::new() }
2150 /// this is always allowed
2152 /// fn bar(alef: A, bet: B) -> X;
2155 /// if req_body is set to true, this is an error
2158 /// This field should only be set to false if the item is inside of a trait
2159 /// definition or extern block. Within an impl block or a module, it should
2160 /// always be set to true.
2164 /// Parsing of functions and methods.
2165 impl<'a> Parser<'a> {
2166 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2169 attrs: &mut AttrVec,
2170 fn_parse_mode: FnParseMode,
2174 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2175 let fn_span = self.token.span;
2176 let header = self.parse_fn_front_matter(vis, case)?; // `const ... fn`
2177 let ident = self.parse_ident()?; // `foo`
2178 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2179 let decl = match self.parse_fn_decl(
2180 fn_parse_mode.req_name,
2182 RecoverReturnSign::Yes,
2186 // If we see `for Ty ...` then user probably meant `impl` item.
2187 if self.token.is_keyword(kw::For) {
2189 return Err(self.sess.create_err(FnTypoWithImpl { fn_span }));
2191 return Err(old_err);
2195 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2197 let mut sig_hi = self.prev_token.span;
2198 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2199 let fn_sig_span = sig_lo.to(sig_hi);
2200 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2203 /// Parse the "body" of a function.
2204 /// This can either be `;` when there's no body,
2205 /// or e.g. a block when the function is a provided one.
2208 attrs: &mut AttrVec,
2212 ) -> PResult<'a, Option<P<Block>>> {
2213 let has_semi = if req_body {
2214 self.token.kind == TokenKind::Semi
2216 // Only include `;` in list of expected tokens if body is not required
2217 self.check(&TokenKind::Semi)
2219 let (inner_attrs, body) = if has_semi {
2220 // Include the trailing semicolon in the span of the signature
2221 self.expect_semi()?;
2222 *sig_hi = self.prev_token.span;
2223 (AttrVec::new(), None)
2224 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2225 self.parse_block_common(self.token.span, BlockCheckMode::Default, false)
2226 .map(|(attrs, body)| (attrs, Some(body)))?
2227 } else if self.token.kind == token::Eq {
2228 // Recover `fn foo() = $expr;`.
2230 let eq_sp = self.prev_token.span;
2231 let _ = self.parse_expr()?;
2232 self.expect_semi()?; // `;`
2233 let span = eq_sp.to(self.prev_token.span);
2234 self.struct_span_err(span, "function body cannot be `= expression;`")
2235 .multipart_suggestion(
2236 "surround the expression with `{` and `}` instead of `=` and `;`",
2237 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2238 Applicability::MachineApplicable,
2241 (AttrVec::new(), Some(self.mk_block_err(span)))
2243 let expected = if req_body {
2244 &[token::OpenDelim(Delimiter::Brace)][..]
2246 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2248 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2249 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2250 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2251 // the AST for typechecking.
2252 err.span_label(ident.span, "while parsing this `fn`");
2258 (AttrVec::new(), None)
2260 attrs.extend(inner_attrs);
2264 /// Is the current token the start of an `FnHeader` / not a valid parse?
2266 /// `check_pub` adds additional `pub` to the checks in case users place it
2267 /// wrongly, can be used to ensure `pub` never comes after `default`.
2268 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2269 // We use an over-approximation here.
2270 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2271 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2272 // only if it wasn't preceded by `default` as `default pub` is invalid.
2273 let quals: &[Symbol] = if check_pub {
2274 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2276 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2278 self.check_keyword_case(kw::Fn, case) // Definitely an `fn`.
2279 // `$qual fn` or `$qual $qual`:
2280 || quals.iter().any(|&kw| self.check_keyword_case(kw, case))
2281 && self.look_ahead(1, |t| {
2282 // `$qual fn`, e.g. `const fn` or `async fn`.
2283 t.is_keyword_case(kw::Fn, case)
2284 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2287 t.is_non_raw_ident_where(|i|
2288 quals.contains(&i.name)
2289 // Rule out 2015 `const async: T = val`.
2292 || case == Case::Insensitive
2293 && t.is_non_raw_ident_where(|i| quals.iter().any(|qual| qual.as_str() == i.name.as_str().to_lowercase()))
2295 // Rule out unsafe extern block.
2296 && !self.is_unsafe_foreign_mod())
2299 || self.check_keyword_case(kw::Extern, case)
2300 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2301 && self.look_ahead(2, |t| t.is_keyword_case(kw::Fn, case))
2304 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2305 /// up to and including the `fn` keyword. The formal grammar is:
2308 /// Extern = "extern" StringLit? ;
2309 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2310 /// FnFrontMatter = FnQual "fn" ;
2313 /// `vis` represents the visibility that was already parsed, if any. Use
2314 /// `Visibility::Inherited` when no visibility is known.
2315 pub(super) fn parse_fn_front_matter(
2317 orig_vis: &Visibility,
2319 ) -> PResult<'a, FnHeader> {
2320 let sp_start = self.token.span;
2321 let constness = self.parse_constness(case);
2323 let async_start_sp = self.token.span;
2324 let asyncness = self.parse_asyncness(case);
2326 let unsafe_start_sp = self.token.span;
2327 let unsafety = self.parse_unsafety(case);
2329 let ext_start_sp = self.token.span;
2330 let ext = self.parse_extern(case);
2332 if let Async::Yes { span, .. } = asyncness {
2333 self.ban_async_in_2015(span);
2336 if !self.eat_keyword_case(kw::Fn, case) {
2337 // It is possible for `expect_one_of` to recover given the contents of
2338 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2339 // account for this.
2340 match self.expect_one_of(&[], &[]) {
2342 Ok(false) => unreachable!(),
2344 // Qualifier keywords ordering check
2350 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2351 // that the keyword is already present and the second instance should be removed.
2352 let wrong_kw = if self.check_keyword(kw::Const) {
2354 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2355 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2357 } else if self.check_keyword(kw::Async) {
2359 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2360 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2362 } else if self.check_keyword(kw::Unsafe) {
2364 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2365 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2371 // The keyword is already present, suggest removal of the second instance
2372 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2373 let original_kw = self
2374 .span_to_snippet(original_sp)
2375 .expect("Span extracted directly from keyword should always work");
2377 err.span_suggestion(
2378 self.token.uninterpolated_span(),
2379 &format!("`{original_kw}` already used earlier, remove this one"),
2381 Applicability::MachineApplicable,
2383 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2385 // The keyword has not been seen yet, suggest correct placement in the function front matter
2386 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2387 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2388 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2389 let misplaced_qual_sp = self.token.uninterpolated_span();
2390 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2392 err.span_suggestion(
2393 correct_pos_sp.to(misplaced_qual_sp),
2394 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2395 format!("{misplaced_qual} {current_qual}"),
2396 Applicability::MachineApplicable,
2397 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2400 // Recover incorrect visibility order such as `async pub`
2401 else if self.check_keyword(kw::Pub) {
2402 let sp = sp_start.to(self.prev_token.span);
2403 if let Ok(snippet) = self.span_to_snippet(sp) {
2404 let current_vis = match self.parse_visibility(FollowedByType::No) {
2411 let vs = pprust::vis_to_string(¤t_vis);
2412 let vs = vs.trim_end();
2414 // There was no explicit visibility
2415 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2416 err.span_suggestion(
2417 sp_start.to(self.prev_token.span),
2418 &format!("visibility `{vs}` must come before `{snippet}`"),
2419 format!("{vs} {snippet}"),
2420 Applicability::MachineApplicable,
2423 // There was an explicit visibility
2425 err.span_suggestion(
2427 "there is already a visibility modifier, remove one",
2429 Applicability::MachineApplicable,
2431 .span_note(orig_vis.span, "explicit visibility first seen here");
2440 Ok(FnHeader { constness, unsafety, asyncness, ext })
2443 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2444 fn ban_async_in_2015(&self, span: Span) {
2445 if span.rust_2015() {
2446 let diag = self.diagnostic();
2447 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2448 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2449 .help_use_latest_edition()
2454 /// Parses the parameter list and result type of a function declaration.
2455 pub(super) fn parse_fn_decl(
2458 ret_allow_plus: AllowPlus,
2459 recover_return_sign: RecoverReturnSign,
2460 ) -> PResult<'a, P<FnDecl>> {
2462 inputs: self.parse_fn_params(req_name)?,
2463 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2467 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2468 pub(super) fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2469 let mut first_param = true;
2470 // Parse the arguments, starting out with `self` being allowed...
2471 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2472 p.recover_diff_marker();
2473 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2475 let lo = p.prev_token.span;
2476 // Skip every token until next possible arg or end.
2477 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2478 // Create a placeholder argument for proper arg count (issue #34264).
2479 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2481 // ...now that we've parsed the first argument, `self` is no longer allowed.
2482 first_param = false;
2485 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2486 self.deduplicate_recovered_params_names(&mut params);
2490 /// Parses a single function parameter.
2492 /// - `self` is syntactically allowed when `first_param` holds.
2493 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2494 let lo = self.token.span;
2495 let attrs = self.parse_outer_attributes()?;
2496 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2497 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2498 if let Some(mut param) = this.parse_self_param()? {
2499 param.attrs = attrs;
2500 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2501 return Ok((res?, TrailingToken::None));
2504 let is_name_required = match this.token.kind {
2505 token::DotDotDot => false,
2506 _ => req_name(this.token.span.edition()),
2508 let (pat, ty) = if is_name_required || this.is_named_param() {
2509 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2510 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2512 let mut err = this.unexpected::<()>().unwrap_err();
2513 return if let Some(ident) =
2514 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2517 Ok((dummy_arg(ident), TrailingToken::None))
2523 this.eat_incorrect_doc_comment_for_param_type();
2524 (pat, this.parse_ty_for_param()?)
2526 debug!("parse_param_general ident_to_pat");
2527 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2528 this.eat_incorrect_doc_comment_for_param_type();
2529 let mut ty = this.parse_ty_for_param();
2531 && this.token != token::Comma
2532 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2534 // This wasn't actually a type, but a pattern looking like a type,
2535 // so we are going to rollback and re-parse for recovery.
2536 ty = this.unexpected();
2540 let ident = Ident::new(kw::Empty, this.prev_token.span);
2541 let bm = BindingAnnotation::NONE;
2542 let pat = this.mk_pat_ident(ty.span, bm, ident);
2545 // If this is a C-variadic argument and we hit an error, return the error.
2546 Err(err) if this.token == token::DotDotDot => return Err(err),
2547 // Recover from attempting to parse the argument as a type without pattern.
2550 this.restore_snapshot(parser_snapshot_before_ty);
2551 this.recover_arg_parse()?
2556 let span = lo.to(this.prev_token.span);
2559 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2560 TrailingToken::None,
2565 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2566 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2567 // Extract an identifier *after* having confirmed that the token is one.
2568 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2569 Some((ident, false)) => {
2573 _ => unreachable!(),
2575 // Is `self` `n` tokens ahead?
2576 let is_isolated_self = |this: &Self, n| {
2577 this.is_keyword_ahead(n, &[kw::SelfLower])
2578 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2580 // Is `mut self` `n` tokens ahead?
2581 let is_isolated_mut_self =
2582 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2583 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2584 let parse_self_possibly_typed = |this: &mut Self, m| {
2585 let eself_ident = expect_self_ident(this);
2586 let eself_hi = this.prev_token.span;
2587 let eself = if this.eat(&token::Colon) {
2588 SelfKind::Explicit(this.parse_ty()?, m)
2592 Ok((eself, eself_ident, eself_hi))
2594 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2595 let recover_self_ptr = |this: &mut Self| {
2596 let msg = "cannot pass `self` by raw pointer";
2597 let span = this.token.span;
2598 this.struct_span_err(span, msg).span_label(span, msg).emit();
2600 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2603 // Parse optional `self` parameter of a method.
2604 // Only a limited set of initial token sequences is considered `self` parameters; anything
2605 // else is parsed as a normal function parameter list, so some lookahead is required.
2606 let eself_lo = self.token.span;
2607 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2608 token::BinOp(token::And) => {
2609 let eself = if is_isolated_self(self, 1) {
2612 SelfKind::Region(None, Mutability::Not)
2613 } else if is_isolated_mut_self(self, 1) {
2617 SelfKind::Region(None, Mutability::Mut)
2618 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2621 let lt = self.expect_lifetime();
2622 SelfKind::Region(Some(lt), Mutability::Not)
2623 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2626 let lt = self.expect_lifetime();
2628 SelfKind::Region(Some(lt), Mutability::Mut)
2633 (eself, expect_self_ident(self), self.prev_token.span)
2636 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2638 recover_self_ptr(self)?
2640 // `*mut self` and `*const self`
2641 token::BinOp(token::Star)
2642 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2646 recover_self_ptr(self)?
2648 // `self` and `self: TYPE`
2649 token::Ident(..) if is_isolated_self(self, 0) => {
2650 parse_self_possibly_typed(self, Mutability::Not)?
2652 // `mut self` and `mut self: TYPE`
2653 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2655 parse_self_possibly_typed(self, Mutability::Mut)?
2657 _ => return Ok(None),
2660 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2661 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2664 fn is_named_param(&self) -> bool {
2665 let offset = match &self.token.kind {
2666 token::Interpolated(nt) => match **nt {
2667 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2670 token::BinOp(token::And) | token::AndAnd => 1,
2671 _ if self.token.is_keyword(kw::Mut) => 1,
2675 self.look_ahead(offset, |t| t.is_ident())
2676 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2679 fn recover_first_param(&mut self) -> &'static str {
2681 .parse_outer_attributes()
2682 .and_then(|_| self.parse_self_param())
2683 .map_err(|e| e.cancel())
2685 Ok(Some(_)) => "method",
2691 enum IsMacroRulesItem {
2692 Yes { has_bang: bool },