1 use crate::errors::{DocCommentDoesNotDocumentAnything, UseEmptyBlockNotSemi};
3 use super::diagnostics::{dummy_arg, ConsumeClosingDelim};
4 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
5 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
8 use rustc_ast::token::{self, Delimiter, TokenKind};
9 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
10 use rustc_ast::util::case::Case;
11 use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
12 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
13 use rustc_ast::{BindingAnnotation, Block, FnDecl, FnSig, Param, SelfKind};
14 use rustc_ast::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData};
15 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
16 use rustc_ast::{MacCall, MacDelimiter};
17 use rustc_ast_pretty::pprust;
18 use rustc_errors::{struct_span_err, Applicability, IntoDiagnostic, PResult, StashKey};
19 use rustc_span::edition::Edition;
20 use rustc_span::lev_distance::lev_distance;
21 use rustc_span::source_map::{self, Span};
22 use rustc_span::symbol::{kw, sym, Ident, Symbol};
23 use rustc_span::DUMMY_SP;
24 use std::convert::TryFrom;
26 use thin_vec::ThinVec;
30 /// Parses a source module as a crate. This is the main entry point for the parser.
31 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
32 let (attrs, items, spans) = self.parse_mod(&token::Eof)?;
33 Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
36 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
37 fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemInfo> {
38 let unsafety = self.parse_unsafety(Case::Sensitive);
39 self.expect_keyword(kw::Mod)?;
40 let id = self.parse_ident()?;
41 let mod_kind = if self.eat(&token::Semi) {
44 self.expect(&token::OpenDelim(Delimiter::Brace))?;
45 let (inner_attrs, items, inner_span) =
46 self.parse_mod(&token::CloseDelim(Delimiter::Brace))?;
47 attrs.extend(inner_attrs);
48 ModKind::Loaded(items, Inline::Yes, inner_span)
50 Ok((id, ItemKind::Mod(unsafety, mod_kind)))
53 /// Parses the contents of a module (inner attributes followed by module items).
57 ) -> PResult<'a, (AttrVec, Vec<P<Item>>, ModSpans)> {
58 let lo = self.token.span;
59 let attrs = self.parse_inner_attributes()?;
61 let post_attr_lo = self.token.span;
62 let mut items = vec![];
63 while let Some(item) = self.parse_item(ForceCollect::No)? {
65 self.maybe_consume_incorrect_semicolon(&items);
69 let token_str = super::token_descr(&self.token);
70 if !self.maybe_consume_incorrect_semicolon(&items) {
71 let msg = &format!("expected item, found {token_str}");
72 let mut err = self.struct_span_err(self.token.span, msg);
73 let label = if self.is_kw_followed_by_ident(kw::Let) {
74 "consider using `const` or `static` instead of `let` for global variables"
78 err.span_label(self.token.span, label);
83 let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
84 let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
85 Ok((attrs, items, mod_spans))
89 pub(super) type ItemInfo = (Ident, ItemKind);
92 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
93 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
94 self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
99 fn_parse_mode: FnParseMode,
100 force_collect: ForceCollect,
101 ) -> PResult<'a, Option<Item>> {
102 let attrs = self.parse_outer_attributes()?;
103 self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
106 pub(super) fn parse_item_common(
111 fn_parse_mode: FnParseMode,
112 force_collect: ForceCollect,
113 ) -> PResult<'a, Option<Item>> {
114 // Don't use `maybe_whole` so that we have precise control
115 // over when we bump the parser
116 if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
117 let mut item = item.clone();
120 attrs.prepend_to_nt_inner(&mut item.attrs);
121 return Ok(Some(item.into_inner()));
124 let mut unclosed_delims = vec![];
126 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
128 this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
129 unclosed_delims.append(&mut this.unclosed_delims);
130 Ok((item?, TrailingToken::None))
133 self.unclosed_delims.append(&mut unclosed_delims);
137 fn parse_item_common_(
142 fn_parse_mode: FnParseMode,
143 ) -> PResult<'a, Option<Item>> {
144 let lo = self.token.span;
145 let vis = self.parse_visibility(FollowedByType::No)?;
146 let mut def = self.parse_defaultness();
147 let kind = self.parse_item_kind(
156 if let Some((ident, kind)) = kind {
157 self.error_on_unconsumed_default(def, &kind);
158 let span = lo.to(self.prev_token.span);
159 let id = DUMMY_NODE_ID;
160 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
161 return Ok(Some(item));
164 // At this point, we have failed to parse an item.
165 self.error_on_unmatched_vis(&vis);
166 self.error_on_unmatched_defaultness(def);
168 self.recover_attrs_no_item(&attrs)?;
173 /// Error in-case a non-inherited visibility was parsed but no item followed.
174 fn error_on_unmatched_vis(&self, vis: &Visibility) {
175 if let VisibilityKind::Inherited = vis.kind {
178 let vs = pprust::vis_to_string(&vis);
179 let vs = vs.trim_end();
180 self.struct_span_err(vis.span, &format!("visibility `{vs}` is not followed by an item"))
181 .span_label(vis.span, "the visibility")
182 .help(&format!("you likely meant to define an item, e.g., `{vs} fn foo() {{}}`"))
186 /// Error in-case a `default` was parsed but no item followed.
187 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
188 if let Defaultness::Default(sp) = def {
189 self.struct_span_err(sp, "`default` is not followed by an item")
190 .span_label(sp, "the `default` qualifier")
191 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
196 /// Error in-case `default` was parsed in an in-appropriate context.
197 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
198 if let Defaultness::Default(span) = def {
199 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
200 self.struct_span_err(span, &msg)
201 .span_label(span, "`default` because of this")
202 .note("only associated `fn`, `const`, and `type` items can be `default`")
207 /// Parses one of the items allowed by the flags.
211 macros_allowed: bool,
214 def: &mut Defaultness,
215 fn_parse_mode: FnParseMode,
217 ) -> PResult<'a, Option<ItemInfo>> {
218 let def_final = def == &Defaultness::Final;
219 let mut def_ = || mem::replace(def, Defaultness::Final);
221 let info = if self.eat_keyword_case(kw::Use, case) {
222 self.parse_use_item()?
223 } else if self.check_fn_front_matter(def_final, case) {
225 let (ident, sig, generics, body) =
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 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::Bracket)`.
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 semicolon_span = self.token.span;
732 // We have to bail or we'll potentially never make progress.
733 let non_item_span = self.token.span;
734 let is_let = self.token.is_keyword(kw::Let);
736 let mut err = self.struct_span_err(non_item_span, "non-item in item list");
737 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
741 "consider using `const` instead of `let` for associated const",
743 Applicability::MachineApplicable,
746 err.span_label(open_brace_span, "item list starts here")
747 .span_label(non_item_span, "non-item starts here")
748 .span_label(self.prev_token.span, "item list ends here");
750 if is_unnecessary_semicolon {
753 "consider removing this semicolon",
755 Applicability::MaybeIncorrect,
761 Ok(Some(item)) => items.extend(item),
763 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
764 err.span_label(open_brace_span, "while parsing this item list starting here")
765 .span_label(self.prev_token.span, "the item list ends here")
774 /// Recover on a doc comment before `}`.
775 fn recover_doc_comment_before_brace(&mut self) -> bool {
776 if let token::DocComment(..) = self.token.kind {
777 if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
782 "found a documentation comment that doesn't document anything",
784 .span_label(self.token.span, "this doc comment doesn't document anything")
786 "doc comments must come before what they document, if a comment was \
797 /// Parses defaultness (i.e., `default` or nothing).
798 fn parse_defaultness(&mut self) -> Defaultness {
799 // We are interested in `default` followed by another identifier.
800 // However, we must avoid keywords that occur as binary operators.
801 // Currently, the only applicable keyword is `as` (`default as Ty`).
802 if self.check_keyword(kw::Default)
803 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
805 self.bump(); // `default`
806 Defaultness::Default(self.prev_token.uninterpolated_span())
812 /// Is this an `(unsafe auto? | auto) trait` item?
813 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
815 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
817 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
820 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
821 fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
822 let unsafety = self.parse_unsafety(Case::Sensitive);
823 // Parse optional `auto` prefix.
824 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
826 self.expect_keyword(kw::Trait)?;
827 let ident = self.parse_ident()?;
828 let mut generics = self.parse_generics()?;
830 // Parse optional colon and supertrait bounds.
831 let had_colon = self.eat(&token::Colon);
832 let span_at_colon = self.prev_token.span;
833 let bounds = if had_colon {
834 self.parse_generic_bounds(Some(self.prev_token.span))?
839 let span_before_eq = self.prev_token.span;
840 if self.eat(&token::Eq) {
841 // It's a trait alias.
843 let span = span_at_colon.to(span_before_eq);
844 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
847 let bounds = self.parse_generic_bounds(None)?;
848 generics.where_clause = self.parse_where_clause()?;
851 let whole_span = lo.to(self.prev_token.span);
852 if is_auto == IsAuto::Yes {
853 let msg = "trait aliases cannot be `auto`";
854 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
856 if let Unsafe::Yes(_) = unsafety {
857 let msg = "trait aliases cannot be `unsafe`";
858 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
861 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
863 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
865 // It's a normal trait.
866 generics.where_clause = self.parse_where_clause()?;
867 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
870 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
875 pub fn parse_impl_item(
877 force_collect: ForceCollect,
878 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
879 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
880 self.parse_assoc_item(fn_parse_mode, force_collect)
883 pub fn parse_trait_item(
885 force_collect: ForceCollect,
886 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
888 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
889 self.parse_assoc_item(fn_parse_mode, force_collect)
892 /// Parses associated items.
895 fn_parse_mode: FnParseMode,
896 force_collect: ForceCollect,
897 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
898 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
899 |Item { attrs, id, span, vis, ident, kind, tokens }| {
900 let kind = match AssocItemKind::try_from(kind) {
902 Err(kind) => match kind {
903 ItemKind::Static(a, _, b) => {
904 self.struct_span_err(span, "associated `static` items are not allowed")
906 AssocItemKind::Const(Defaultness::Final, a, b)
908 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
911 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
916 /// Parses a `type` alias with the following grammar:
918 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
920 /// The `"type"` has already been eaten.
921 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
922 let ident = self.parse_ident()?;
923 let mut generics = self.parse_generics()?;
925 // Parse optional colon and param bounds.
927 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
928 let before_where_clause = self.parse_where_clause()?;
930 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
932 let after_where_clause = self.parse_where_clause()?;
934 let where_clauses = (
935 TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
936 TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
938 let where_predicates_split = before_where_clause.predicates.len();
939 let mut predicates = before_where_clause.predicates;
940 predicates.extend(after_where_clause.predicates.into_iter());
941 let where_clause = WhereClause {
942 has_where_token: before_where_clause.has_where_token
943 || after_where_clause.has_where_token,
947 generics.where_clause = where_clause;
953 ItemKind::TyAlias(Box::new(TyAlias {
957 where_predicates_split,
964 /// Parses a `UseTree`.
967 /// USE_TREE = [`::`] `*` |
968 /// [`::`] `{` USE_TREE_LIST `}` |
970 /// PATH `::` `{` USE_TREE_LIST `}` |
971 /// PATH [`as` IDENT]
973 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
974 let lo = self.token.span;
977 ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo(), tokens: None };
978 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
979 || self.check(&token::BinOp(token::Star))
980 || self.is_import_coupler()
982 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
983 let mod_sep_ctxt = self.token.span.ctxt();
984 if self.eat(&token::ModSep) {
987 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
990 self.parse_use_tree_glob_or_nested()?
992 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
993 prefix = self.parse_path(PathStyle::Mod)?;
995 if self.eat(&token::ModSep) {
996 self.parse_use_tree_glob_or_nested()?
998 // Recover from using a colon as path separator.
999 while self.eat_noexpect(&token::Colon) {
1000 self.struct_span_err(self.prev_token.span, "expected `::`, found `:`")
1001 .span_suggestion_short(
1002 self.prev_token.span,
1005 Applicability::MachineApplicable,
1007 .note_once("import paths are delimited using `::`")
1010 // We parse the rest of the path and append it to the original prefix.
1011 self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
1012 prefix.span = lo.to(self.prev_token.span);
1015 UseTreeKind::Simple(self.parse_rename()?)
1019 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
1022 /// Parses `*` or `{...}`.
1023 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1024 Ok(if self.eat(&token::BinOp(token::Star)) {
1027 UseTreeKind::Nested(self.parse_use_tree_list()?)
1031 /// Parses a `UseTreeKind::Nested(list)`.
1034 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
1036 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1037 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
1041 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1042 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1045 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1046 match self.token.ident() {
1047 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1051 _ => self.parse_ident(),
1055 /// Parses `extern crate` links.
1059 /// ```ignore (illustrative)
1060 /// extern crate foo;
1061 /// extern crate bar as foo;
1063 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1064 // Accept `extern crate name-like-this` for better diagnostics
1065 let orig_name = self.parse_crate_name_with_dashes()?;
1066 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1067 (rename, Some(orig_name.name))
1071 self.expect_semi()?;
1072 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1075 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1076 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1077 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1079 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1080 self.parse_path_segment_ident()
1084 let mut idents = vec![];
1085 let mut replacement = vec![];
1086 let mut fixed_crate_name = false;
1087 // Accept `extern crate name-like-this` for better diagnostics.
1088 let dash = token::BinOp(token::BinOpToken::Minus);
1089 if self.token == dash {
1090 // Do not include `-` as part of the expected tokens list.
1091 while self.eat(&dash) {
1092 fixed_crate_name = true;
1093 replacement.push((self.prev_token.span, "_".to_string()));
1094 idents.push(self.parse_ident()?);
1097 if fixed_crate_name {
1098 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1099 let mut fixed_name = ident.name.to_string();
1100 for part in idents {
1101 fixed_name.push_str(&format!("_{}", part.name));
1103 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1105 self.struct_span_err(fixed_name_sp, error_msg)
1106 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1107 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1113 /// Parses `extern` for foreign ABIs modules.
1115 /// `extern` is expected to have been consumed before calling this method.
1119 /// ```ignore (only-for-syntax-highlight)
1123 fn parse_item_foreign_mod(
1125 attrs: &mut AttrVec,
1126 mut unsafety: Unsafe,
1127 ) -> PResult<'a, ItemInfo> {
1128 let abi = self.parse_abi(); // ABI?
1129 if unsafety == Unsafe::No
1130 && self.token.is_keyword(kw::Unsafe)
1131 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1133 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1135 unsafety = Unsafe::Yes(self.token.span);
1136 self.eat_keyword(kw::Unsafe);
1138 let module = ast::ForeignMod {
1141 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1143 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1146 /// Parses a foreign item (one in an `extern { ... }` block).
1147 pub fn parse_foreign_item(
1149 force_collect: ForceCollect,
1150 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1151 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1152 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1153 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1154 let kind = match ForeignItemKind::try_from(kind) {
1156 Err(kind) => match kind {
1157 ItemKind::Const(_, a, b) => {
1158 self.error_on_foreign_const(span, ident);
1159 ForeignItemKind::Static(a, Mutability::Not, b)
1161 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1164 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1169 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1170 let span = self.sess.source_map().guess_head_span(span);
1171 let descr = kind.descr();
1172 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1173 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1178 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1179 self.struct_span_err(ident.span, "extern items cannot be `const`")
1181 span.with_hi(ident.span.lo()),
1182 "try using a static value",
1184 Applicability::MachineApplicable,
1186 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1190 fn is_unsafe_foreign_mod(&self) -> bool {
1191 self.token.is_keyword(kw::Unsafe)
1192 && self.is_keyword_ahead(1, &[kw::Extern])
1194 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1195 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1199 fn is_static_global(&mut self) -> bool {
1200 if self.check_keyword(kw::Static) {
1201 // Check if this could be a closure.
1202 !self.look_ahead(1, |token| {
1203 if token.is_keyword(kw::Move) {
1206 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1213 /// Recover on `const mut` with `const` already eaten.
1214 fn recover_const_mut(&mut self, const_span: Span) {
1215 if self.eat_keyword(kw::Mut) {
1216 let span = self.prev_token.span;
1217 self.struct_span_err(span, "const globals cannot be mutable")
1218 .span_label(span, "cannot be mutable")
1221 "you might want to declare a static instead",
1223 Applicability::MaybeIncorrect,
1226 } else if self.eat_keyword(kw::Let) {
1227 let span = self.prev_token.span;
1228 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1230 const_span.to(span),
1233 Applicability::MaybeIncorrect,
1239 /// Recover on `const impl` with `const` already eaten.
1240 fn recover_const_impl(
1243 attrs: &mut AttrVec,
1244 defaultness: Defaultness,
1245 ) -> PResult<'a, ItemInfo> {
1246 let impl_span = self.token.span;
1247 let mut err = self.expected_ident_found();
1249 // Only try to recover if this is implementing a trait for a type
1250 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1251 Ok(impl_info) => impl_info,
1252 Err(recovery_error) => {
1253 // Recovery failed, raise the "expected identifier" error
1254 recovery_error.cancel();
1259 match &mut impl_info.1 {
1260 ItemKind::Impl(box Impl { of_trait: Some(trai), constness, .. }) => {
1261 *constness = Const::Yes(const_span);
1263 let before_trait = trai.path.span.shrink_to_lo();
1264 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1265 err.multipart_suggestion(
1266 "you might have meant to write a const trait impl",
1267 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1268 Applicability::MaybeIncorrect,
1272 ItemKind::Impl { .. } => return Err(err),
1273 _ => unreachable!(),
1279 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1280 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1282 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1283 fn parse_item_global(
1285 m: Option<Mutability>,
1286 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1287 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1289 // Parse the type of a `const` or `static mut?` item.
1290 // That is, the `":" $ty` fragment.
1291 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1293 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1294 (true, false) => self.parse_ty()?,
1295 (colon, _) => self.recover_missing_const_type(colon, m),
1298 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1299 self.expect_semi()?;
1303 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1304 /// This means that the type is missing.
1305 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1306 // Construct the error and stash it away with the hope
1307 // that typeck will later enrich the error with a type.
1308 let kind = match m {
1309 Some(Mutability::Mut) => "static mut",
1310 Some(Mutability::Not) => "static",
1314 let colon = match colon_present {
1319 let span = self.prev_token.span.shrink_to_hi();
1320 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1321 err.span_suggestion(
1323 "provide a type for the item",
1324 format!("{colon} <type>"),
1325 Applicability::HasPlaceholders,
1327 err.stash(span, StashKey::ItemNoType);
1329 // The user intended that the type be inferred,
1330 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1331 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1334 /// Parses an enum declaration.
1335 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1336 if self.token.is_keyword(kw::Struct) {
1337 let span = self.prev_token.span.to(self.token.span);
1338 let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1339 err.span_suggestion(
1341 "replace `enum struct` with",
1343 Applicability::MachineApplicable,
1345 if self.look_ahead(1, |t| t.is_ident()) {
1353 let id = self.parse_ident()?;
1354 let mut generics = self.parse_generics()?;
1355 generics.where_clause = self.parse_where_clause()?;
1357 // Possibly recover `enum Foo;` instead of `enum Foo {}`
1358 let (variants, _) = if self.token == TokenKind::Semi {
1359 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1363 self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1365 e.span_label(id.span, "while parsing this enum");
1366 self.recover_stmt();
1372 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1373 Ok((id, ItemKind::Enum(enum_definition, generics)))
1376 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1377 let variant_attrs = self.parse_outer_attributes()?;
1378 self.collect_tokens_trailing_token(
1381 |this, variant_attrs| {
1382 let vlo = this.token.span;
1384 let vis = this.parse_visibility(FollowedByType::No)?;
1385 if !this.recover_nested_adt_item(kw::Enum)? {
1386 return Ok((None, TrailingToken::None));
1388 let ident = this.parse_field_ident("enum", vlo)?;
1390 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1391 // Parse a struct variant.
1392 let (fields, recovered) =
1393 this.parse_record_struct_body("struct", ident.span, false)?;
1394 VariantData::Struct(fields, recovered)
1395 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1396 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1398 VariantData::Unit(DUMMY_NODE_ID)
1402 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1404 let vr = ast::Variant {
1408 attrs: variant_attrs,
1411 span: vlo.to(this.prev_token.span),
1412 is_placeholder: false,
1415 Ok((Some(vr), TrailingToken::MaybeComma))
1420 /// Parses `struct Foo { ... }`.
1421 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1422 let class_name = self.parse_ident()?;
1424 let mut generics = self.parse_generics()?;
1426 // There is a special case worth noting here, as reported in issue #17904.
1427 // If we are parsing a tuple struct it is the case that the where clause
1428 // should follow the field list. Like so:
1430 // struct Foo<T>(T) where T: Copy;
1432 // If we are parsing a normal record-style struct it is the case
1433 // that the where clause comes before the body, and after the generics.
1434 // So if we look ahead and see a brace or a where-clause we begin
1435 // parsing a record style struct.
1437 // Otherwise if we look ahead and see a paren we parse a tuple-style
1440 let vdata = if self.token.is_keyword(kw::Where) {
1441 generics.where_clause = self.parse_where_clause()?;
1442 if self.eat(&token::Semi) {
1443 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1444 VariantData::Unit(DUMMY_NODE_ID)
1446 // If we see: `struct Foo<T> where T: Copy { ... }`
1447 let (fields, recovered) = self.parse_record_struct_body(
1450 generics.where_clause.has_where_token,
1452 VariantData::Struct(fields, recovered)
1454 // No `where` so: `struct Foo<T>;`
1455 } else if self.eat(&token::Semi) {
1456 VariantData::Unit(DUMMY_NODE_ID)
1457 // Record-style struct definition
1458 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1459 let (fields, recovered) = self.parse_record_struct_body(
1462 generics.where_clause.has_where_token,
1464 VariantData::Struct(fields, recovered)
1465 // Tuple-style struct definition with optional where-clause.
1466 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1467 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1468 generics.where_clause = self.parse_where_clause()?;
1469 self.expect_semi()?;
1472 let token_str = super::token_descr(&self.token);
1474 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1476 let mut err = self.struct_span_err(self.token.span, msg);
1477 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1481 Ok((class_name, ItemKind::Struct(vdata, generics)))
1484 /// Parses `union Foo { ... }`.
1485 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1486 let class_name = self.parse_ident()?;
1488 let mut generics = self.parse_generics()?;
1490 let vdata = if self.token.is_keyword(kw::Where) {
1491 generics.where_clause = self.parse_where_clause()?;
1492 let (fields, recovered) = self.parse_record_struct_body(
1495 generics.where_clause.has_where_token,
1497 VariantData::Struct(fields, recovered)
1498 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1499 let (fields, recovered) = self.parse_record_struct_body(
1502 generics.where_clause.has_where_token,
1504 VariantData::Struct(fields, recovered)
1506 let token_str = super::token_descr(&self.token);
1507 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1508 let mut err = self.struct_span_err(self.token.span, msg);
1509 err.span_label(self.token.span, "expected `where` or `{` after union name");
1513 Ok((class_name, ItemKind::Union(vdata, generics)))
1516 fn parse_record_struct_body(
1521 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1522 let mut fields = Vec::new();
1523 let mut recovered = false;
1524 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1525 while self.token != token::CloseDelim(Delimiter::Brace) {
1526 let field = self.parse_field_def(adt_ty).map_err(|e| {
1527 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1532 Ok(field) => fields.push(field),
1534 err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1540 self.eat(&token::CloseDelim(Delimiter::Brace));
1542 let token_str = super::token_descr(&self.token);
1544 "expected {}`{{` after struct name, found {}",
1545 if parsed_where { "" } else { "`where`, or " },
1548 let mut err = self.struct_span_err(self.token.span, msg);
1552 "expected {}`{{` after struct name",
1553 if parsed_where { "" } else { "`where`, or " }
1559 Ok((fields, recovered))
1562 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1563 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1564 // Unit like structs are handled in parse_item_struct function
1565 self.parse_paren_comma_seq(|p| {
1566 let attrs = p.parse_outer_attributes()?;
1567 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1568 let lo = p.token.span;
1569 let vis = p.parse_visibility(FollowedByType::Yes)?;
1570 let ty = p.parse_ty()?;
1574 span: lo.to(ty.span),
1580 is_placeholder: false,
1582 TrailingToken::MaybeComma,
1589 /// Parses an element of a struct declaration.
1590 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1591 let attrs = self.parse_outer_attributes()?;
1592 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1593 let lo = this.token.span;
1594 let vis = this.parse_visibility(FollowedByType::No)?;
1595 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1599 /// Parses a structure field declaration.
1600 fn parse_single_struct_field(
1606 ) -> PResult<'a, FieldDef> {
1607 let mut seen_comma: bool = false;
1608 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1609 if self.token == token::Comma {
1612 if self.eat(&token::Semi) {
1613 let sp = self.prev_token.span;
1614 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1615 err.span_suggestion_short(
1617 "replace `;` with `,`",
1619 Applicability::MachineApplicable,
1623 match self.token.kind {
1627 token::CloseDelim(Delimiter::Brace) => {}
1628 token::DocComment(..) => {
1629 let previous_span = self.prev_token.span;
1630 let mut err = DocCommentDoesNotDocumentAnything {
1631 span: self.token.span,
1632 missing_comma: None,
1634 self.bump(); // consume the doc comment
1635 let comma_after_doc_seen = self.eat(&token::Comma);
1636 // `seen_comma` is always false, because we are inside doc block
1637 // condition is here to make code more readable
1638 if !seen_comma && comma_after_doc_seen {
1641 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1642 self.sess.emit_err(err);
1645 let sp = previous_span.shrink_to_hi();
1646 err.missing_comma = Some(sp);
1648 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1652 let sp = self.prev_token.span.shrink_to_hi();
1653 let mut err = self.struct_span_err(
1655 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1658 // Try to recover extra trailing angle brackets
1659 let mut recovered = false;
1660 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1661 if let Some(last_segment) = segments.last() {
1662 recovered = self.check_trailing_angle_brackets(
1664 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1667 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1669 self.eat(&token::Comma);
1670 // `check_trailing_angle_brackets` already emitted a nicer error
1671 // NOTE(eddyb) this was `.cancel()`, but `err`
1672 // gets returned, so we can't fully defuse it.
1678 if self.token.is_ident()
1679 || (self.token.kind == TokenKind::Pound
1680 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1682 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1683 // emit the diagnostic and keep going
1684 err.span_suggestion(
1686 "try adding a comma",
1688 Applicability::MachineApplicable,
1695 // Make sure an error was emitted (either by recovering an angle bracket,
1696 // or by finding an identifier as the next token), since we're
1697 // going to continue parsing
1698 assert!(self.sess.span_diagnostic.has_errors().is_some());
1707 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1708 if let Err(mut err) = self.expect(&token::Colon) {
1709 let sm = self.sess.source_map();
1710 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1711 let semi_typo = self.token.kind == token::Semi
1712 && self.look_ahead(1, |t| {
1714 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1715 // when there's no type and `;` was used instead of a comma.
1716 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1717 (Ok(l), Ok(r)) => l.line == r.line,
1721 if eq_typo || semi_typo {
1723 // Gracefully handle small typos.
1724 err.span_suggestion_short(
1725 self.prev_token.span,
1726 "field names and their types are separated with `:`",
1728 Applicability::MachineApplicable,
1738 /// Parses a structure field.
1739 fn parse_name_and_ty(
1745 ) -> PResult<'a, FieldDef> {
1746 let name = self.parse_field_ident(adt_ty, lo)?;
1747 self.expect_field_ty_separator()?;
1748 let ty = self.parse_ty()?;
1749 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1750 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1751 .span_suggestion_verbose(
1753 "write a path separator here",
1755 Applicability::MaybeIncorrect,
1759 if self.token.kind == token::Eq {
1761 let const_expr = self.parse_anon_const_expr()?;
1762 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1763 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1766 "remove this unsupported default value",
1768 Applicability::MachineApplicable,
1773 span: lo.to(self.prev_token.span),
1779 is_placeholder: false,
1783 /// Parses a field identifier. Specialized version of `parse_ident_common`
1784 /// for better diagnostics and suggestions.
1785 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1786 let (ident, is_raw) = self.ident_or_err()?;
1787 if !is_raw && ident.is_reserved() {
1788 let snapshot = self.create_snapshot_for_diagnostic();
1789 let err = if self.check_fn_front_matter(false, Case::Sensitive) {
1790 let inherited_vis = Visibility {
1791 span: rustc_span::DUMMY_SP,
1792 kind: VisibilityKind::Inherited,
1795 // We use `parse_fn` to get a span for the function
1796 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1797 match self.parse_fn(
1798 &mut AttrVec::new(),
1805 let mut err = self.struct_span_err(
1806 lo.to(self.prev_token.span),
1807 &format!("functions are not allowed in {adt_ty} definitions"),
1810 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1812 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1817 self.restore_snapshot(snapshot);
1818 self.expected_ident_found()
1821 } else if self.eat_keyword(kw::Struct) {
1822 match self.parse_item_struct() {
1824 let mut err = self.struct_span_err(
1825 lo.with_hi(ident.span.hi()),
1826 &format!("structs are not allowed in {adt_ty} definitions"),
1828 err.help("consider creating a new `struct` definition instead of nesting");
1833 self.restore_snapshot(snapshot);
1834 self.expected_ident_found()
1838 let mut err = self.expected_ident_found();
1839 if self.eat_keyword_noexpect(kw::Let)
1840 && let removal_span = self.prev_token.span.until(self.token.span)
1841 && let Ok(ident) = self.parse_ident_common(false)
1842 // Cancel this error, we don't need it.
1843 .map_err(|err| err.cancel())
1844 && self.token.kind == TokenKind::Colon
1846 err.span_suggestion(
1848 "remove this `let` keyword",
1850 Applicability::MachineApplicable,
1852 err.note("the `let` keyword is not allowed in `struct` fields");
1853 err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1857 self.restore_snapshot(snapshot);
1867 /// Parses a declarative macro 2.0 definition.
1868 /// The `macro` keyword has already been parsed.
1870 /// MacBody = "{" TOKEN_STREAM "}" ;
1871 /// MacParams = "(" TOKEN_STREAM ")" ;
1872 /// DeclMac = "macro" Ident MacParams? MacBody ;
1874 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1875 let ident = self.parse_ident()?;
1876 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1877 self.parse_delim_args()? // `MacBody`
1878 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1879 let params = self.parse_token_tree(); // `MacParams`
1880 let pspan = params.span();
1881 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1882 return self.unexpected();
1884 let body = self.parse_token_tree(); // `MacBody`
1885 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1886 let bspan = body.span();
1887 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1888 let tokens = TokenStream::new(vec![params, arrow, body]);
1889 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1890 P(DelimArgs { dspan, delim: MacDelimiter::Brace, tokens })
1892 return self.unexpected();
1895 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1896 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1899 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1900 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1901 if self.check_keyword(kw::MacroRules) {
1902 let macro_rules_span = self.token.span;
1904 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1905 return IsMacroRulesItem::Yes { has_bang: true };
1906 } else if self.look_ahead(1, |t| (t.is_ident())) {
1908 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1913 Applicability::MachineApplicable,
1917 return IsMacroRulesItem::Yes { has_bang: false };
1921 IsMacroRulesItem::No
1924 /// Parses a `macro_rules! foo { ... }` declarative macro.
1925 fn parse_item_macro_rules(
1929 ) -> PResult<'a, ItemInfo> {
1930 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1933 self.expect(&token::Not)?; // `!`
1935 let ident = self.parse_ident()?;
1937 if self.eat(&token::Not) {
1938 // Handle macro_rules! foo!
1939 let span = self.prev_token.span;
1940 self.struct_span_err(span, "macro names aren't followed by a `!`")
1941 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1945 let body = self.parse_delim_args()?;
1946 self.eat_semi_for_macro_if_needed(&body);
1947 self.complain_if_pub_macro(vis, true);
1949 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1952 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1953 /// If that's not the case, emit an error.
1954 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1955 if let VisibilityKind::Inherited = vis.kind {
1959 let vstr = pprust::vis_to_string(vis);
1960 let vstr = vstr.trim_end();
1962 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1963 self.struct_span_err(vis.span, &msg)
1966 "try exporting the macro",
1968 Applicability::MaybeIncorrect, // speculative
1972 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1975 "remove the visibility",
1977 Applicability::MachineApplicable,
1979 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1984 fn eat_semi_for_macro_if_needed(&mut self, args: &DelimArgs) {
1985 if args.need_semicolon() && !self.eat(&token::Semi) {
1986 self.report_invalid_macro_expansion_item(args);
1990 fn report_invalid_macro_expansion_item(&self, args: &DelimArgs) {
1991 let span = args.dspan.entire();
1992 let mut err = self.struct_span_err(
1994 "macros that expand to items must be delimited with braces or followed by a semicolon",
1996 // FIXME: This will make us not emit the help even for declarative
1997 // macros within the same crate (that we can fix), which is sad.
1998 if !span.from_expansion() {
1999 if self.unclosed_delims.is_empty() {
2000 let DelimSpan { open, close } = args.dspan;
2001 err.multipart_suggestion(
2002 "change the delimiters to curly braces",
2003 vec![(open, "{".to_string()), (close, '}'.to_string())],
2004 Applicability::MaybeIncorrect,
2007 err.span_suggestion(
2009 "change the delimiters to curly braces",
2011 Applicability::HasPlaceholders,
2014 err.span_suggestion(
2015 span.shrink_to_hi(),
2018 Applicability::MaybeIncorrect,
2024 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
2025 /// it is, we try to parse the item and report error about nested types.
2026 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2027 if (self.token.is_keyword(kw::Enum)
2028 || self.token.is_keyword(kw::Struct)
2029 || self.token.is_keyword(kw::Union))
2030 && self.look_ahead(1, |t| t.is_ident())
2032 let kw_token = self.token.clone();
2033 let kw_str = pprust::token_to_string(&kw_token);
2034 let item = self.parse_item(ForceCollect::No)?;
2036 self.struct_span_err(
2038 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
2042 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2044 Applicability::MaybeIncorrect,
2047 // We successfully parsed the item but we must inform the caller about nested problem.
2054 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2056 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2058 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2059 /// were allowed to omit parameter names. In 2018, they became required.
2060 type ReqName = fn(Edition) -> bool;
2062 /// Parsing configuration for functions.
2064 /// The syntax of function items is slightly different within trait definitions,
2065 /// impl blocks, and modules. It is still parsed using the same code, just with
2066 /// different flags set, so that even when the input is wrong and produces a parse
2067 /// error, it still gets into the AST and the rest of the parser and
2068 /// type checker can run.
2069 #[derive(Clone, Copy)]
2070 pub(crate) struct FnParseMode {
2071 /// A function pointer that decides if, per-parameter `p`, `p` must have a
2072 /// pattern or just a type. This field affects parsing of the parameters list.
2075 /// fn foo(alef: A) -> X { X::new() }
2076 /// -----^^ affects parsing this part of the function signature
2078 /// if req_name returns false, then this name is optional
2083 /// if req_name returns true, this is an error
2086 /// Calling this function pointer should only return false if:
2088 /// * The item is being parsed inside of a trait definition.
2089 /// Within an impl block or a module, it should always evaluate
2091 /// * The span is from Edition 2015. In particular, you can get a
2092 /// 2015 span inside a 2021 crate using macros.
2093 pub req_name: ReqName,
2094 /// If this flag is set to `true`, then plain, semicolon-terminated function
2095 /// prototypes are not allowed here.
2098 /// fn foo(alef: A) -> X { X::new() }
2101 /// this is always allowed
2103 /// fn bar(alef: A, bet: B) -> X;
2106 /// if req_body is set to true, this is an error
2109 /// This field should only be set to false if the item is inside of a trait
2110 /// definition or extern block. Within an impl block or a module, it should
2111 /// always be set to true.
2115 /// Parsing of functions and methods.
2116 impl<'a> Parser<'a> {
2117 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2120 attrs: &mut AttrVec,
2121 fn_parse_mode: FnParseMode,
2125 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2126 let header = self.parse_fn_front_matter(vis, case)?; // `const ... fn`
2127 let ident = self.parse_ident()?; // `foo`
2128 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2130 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
2131 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2133 let mut sig_hi = self.prev_token.span;
2134 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2135 let fn_sig_span = sig_lo.to(sig_hi);
2136 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2139 /// Parse the "body" of a function.
2140 /// This can either be `;` when there's no body,
2141 /// or e.g. a block when the function is a provided one.
2144 attrs: &mut AttrVec,
2148 ) -> PResult<'a, Option<P<Block>>> {
2149 let has_semi = if req_body {
2150 self.token.kind == TokenKind::Semi
2152 // Only include `;` in list of expected tokens if body is not required
2153 self.check(&TokenKind::Semi)
2155 let (inner_attrs, body) = if has_semi {
2156 // Include the trailing semicolon in the span of the signature
2157 self.expect_semi()?;
2158 *sig_hi = self.prev_token.span;
2159 (AttrVec::new(), None)
2160 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2161 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2162 } else if self.token.kind == token::Eq {
2163 // Recover `fn foo() = $expr;`.
2165 let eq_sp = self.prev_token.span;
2166 let _ = self.parse_expr()?;
2167 self.expect_semi()?; // `;`
2168 let span = eq_sp.to(self.prev_token.span);
2169 self.struct_span_err(span, "function body cannot be `= expression;`")
2170 .multipart_suggestion(
2171 "surround the expression with `{` and `}` instead of `=` and `;`",
2172 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2173 Applicability::MachineApplicable,
2176 (AttrVec::new(), Some(self.mk_block_err(span)))
2178 let expected = if req_body {
2179 &[token::OpenDelim(Delimiter::Brace)][..]
2181 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2183 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2184 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2185 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2186 // the AST for typechecking.
2187 err.span_label(ident.span, "while parsing this `fn`");
2193 (AttrVec::new(), None)
2195 attrs.extend(inner_attrs);
2199 /// Is the current token the start of an `FnHeader` / not a valid parse?
2201 /// `check_pub` adds additional `pub` to the checks in case users place it
2202 /// wrongly, can be used to ensure `pub` never comes after `default`.
2203 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool {
2204 // We use an over-approximation here.
2205 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2206 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2207 // only if it wasn't preceded by `default` as `default pub` is invalid.
2208 let quals: &[Symbol] = if check_pub {
2209 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2211 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2213 self.check_keyword_case(kw::Fn, case) // Definitely an `fn`.
2214 // `$qual fn` or `$qual $qual`:
2215 || quals.iter().any(|&kw| self.check_keyword_case(kw, case))
2216 && self.look_ahead(1, |t| {
2217 // `$qual fn`, e.g. `const fn` or `async fn`.
2218 t.is_keyword_case(kw::Fn, case)
2219 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2222 t.is_non_raw_ident_where(|i|
2223 quals.contains(&i.name)
2224 // Rule out 2015 `const async: T = val`.
2227 || case == Case::Insensitive
2228 && t.is_non_raw_ident_where(|i| quals.iter().any(|qual| qual.as_str() == i.name.as_str().to_lowercase()))
2230 // Rule out unsafe extern block.
2231 && !self.is_unsafe_foreign_mod())
2234 || self.check_keyword_case(kw::Extern, case)
2235 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2236 && self.look_ahead(2, |t| t.is_keyword_case(kw::Fn, case))
2239 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2240 /// up to and including the `fn` keyword. The formal grammar is:
2243 /// Extern = "extern" StringLit? ;
2244 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2245 /// FnFrontMatter = FnQual "fn" ;
2248 /// `vis` represents the visibility that was already parsed, if any. Use
2249 /// `Visibility::Inherited` when no visibility is known.
2250 pub(super) fn parse_fn_front_matter(
2252 orig_vis: &Visibility,
2254 ) -> PResult<'a, FnHeader> {
2255 let sp_start = self.token.span;
2256 let constness = self.parse_constness(case);
2258 let async_start_sp = self.token.span;
2259 let asyncness = self.parse_asyncness(case);
2261 let unsafe_start_sp = self.token.span;
2262 let unsafety = self.parse_unsafety(case);
2264 let ext_start_sp = self.token.span;
2265 let ext = self.parse_extern(case);
2267 if let Async::Yes { span, .. } = asyncness {
2268 self.ban_async_in_2015(span);
2271 if !self.eat_keyword_case(kw::Fn, case) {
2272 // It is possible for `expect_one_of` to recover given the contents of
2273 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2274 // account for this.
2275 match self.expect_one_of(&[], &[]) {
2277 Ok(false) => unreachable!(),
2279 // Qualifier keywords ordering check
2285 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2286 // that the keyword is already present and the second instance should be removed.
2287 let wrong_kw = if self.check_keyword(kw::Const) {
2289 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2290 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2292 } else if self.check_keyword(kw::Async) {
2294 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2295 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2297 } else if self.check_keyword(kw::Unsafe) {
2299 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2300 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2306 // The keyword is already present, suggest removal of the second instance
2307 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2308 let original_kw = self
2309 .span_to_snippet(original_sp)
2310 .expect("Span extracted directly from keyword should always work");
2312 err.span_suggestion(
2313 self.token.uninterpolated_span(),
2314 &format!("`{original_kw}` already used earlier, remove this one"),
2316 Applicability::MachineApplicable,
2318 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2320 // The keyword has not been seen yet, suggest correct placement in the function front matter
2321 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2322 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2323 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2324 let misplaced_qual_sp = self.token.uninterpolated_span();
2325 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2327 err.span_suggestion(
2328 correct_pos_sp.to(misplaced_qual_sp),
2329 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2330 format!("{misplaced_qual} {current_qual}"),
2331 Applicability::MachineApplicable,
2332 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2335 // Recover incorrect visibility order such as `async pub`
2336 else if self.check_keyword(kw::Pub) {
2337 let sp = sp_start.to(self.prev_token.span);
2338 if let Ok(snippet) = self.span_to_snippet(sp) {
2339 let current_vis = match self.parse_visibility(FollowedByType::No) {
2346 let vs = pprust::vis_to_string(¤t_vis);
2347 let vs = vs.trim_end();
2349 // There was no explicit visibility
2350 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2351 err.span_suggestion(
2352 sp_start.to(self.prev_token.span),
2353 &format!("visibility `{vs}` must come before `{snippet}`"),
2354 format!("{vs} {snippet}"),
2355 Applicability::MachineApplicable,
2358 // There was an explicit visibility
2360 err.span_suggestion(
2362 "there is already a visibility modifier, remove one",
2364 Applicability::MachineApplicable,
2366 .span_note(orig_vis.span, "explicit visibility first seen here");
2375 Ok(FnHeader { constness, unsafety, asyncness, ext })
2378 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2379 fn ban_async_in_2015(&self, span: Span) {
2380 if span.rust_2015() {
2381 let diag = self.diagnostic();
2382 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2383 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2384 .help_use_latest_edition()
2389 /// Parses the parameter list and result type of a function declaration.
2390 pub(super) fn parse_fn_decl(
2393 ret_allow_plus: AllowPlus,
2394 recover_return_sign: RecoverReturnSign,
2395 ) -> PResult<'a, P<FnDecl>> {
2397 inputs: self.parse_fn_params(req_name)?,
2398 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2402 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2403 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2404 let mut first_param = true;
2405 // Parse the arguments, starting out with `self` being allowed...
2406 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2407 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2409 let lo = p.prev_token.span;
2410 // Skip every token until next possible arg or end.
2411 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2412 // Create a placeholder argument for proper arg count (issue #34264).
2413 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2415 // ...now that we've parsed the first argument, `self` is no longer allowed.
2416 first_param = false;
2419 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2420 self.deduplicate_recovered_params_names(&mut params);
2424 /// Parses a single function parameter.
2426 /// - `self` is syntactically allowed when `first_param` holds.
2427 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2428 let lo = self.token.span;
2429 let attrs = self.parse_outer_attributes()?;
2430 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2431 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2432 if let Some(mut param) = this.parse_self_param()? {
2433 param.attrs = attrs;
2434 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2435 return Ok((res?, TrailingToken::None));
2438 let is_name_required = match this.token.kind {
2439 token::DotDotDot => false,
2440 _ => req_name(this.token.span.edition()),
2442 let (pat, ty) = if is_name_required || this.is_named_param() {
2443 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2445 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2447 let mut err = this.unexpected::<()>().unwrap_err();
2448 return if let Some(ident) =
2449 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2452 Ok((dummy_arg(ident), TrailingToken::None))
2458 this.eat_incorrect_doc_comment_for_param_type();
2459 (pat, this.parse_ty_for_param()?)
2461 debug!("parse_param_general ident_to_pat");
2462 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2463 this.eat_incorrect_doc_comment_for_param_type();
2464 let mut ty = this.parse_ty_for_param();
2466 && this.token != token::Comma
2467 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2469 // This wasn't actually a type, but a pattern looking like a type,
2470 // so we are going to rollback and re-parse for recovery.
2471 ty = this.unexpected();
2475 let ident = Ident::new(kw::Empty, this.prev_token.span);
2476 let bm = BindingAnnotation::NONE;
2477 let pat = this.mk_pat_ident(ty.span, bm, ident);
2480 // If this is a C-variadic argument and we hit an error, return the error.
2481 Err(err) if this.token == token::DotDotDot => return Err(err),
2482 // Recover from attempting to parse the argument as a type without pattern.
2485 this.restore_snapshot(parser_snapshot_before_ty);
2486 this.recover_arg_parse()?
2491 let span = lo.to(this.prev_token.span);
2494 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2495 TrailingToken::None,
2500 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2501 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2502 // Extract an identifier *after* having confirmed that the token is one.
2503 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2504 Some((ident, false)) => {
2508 _ => unreachable!(),
2510 // Is `self` `n` tokens ahead?
2511 let is_isolated_self = |this: &Self, n| {
2512 this.is_keyword_ahead(n, &[kw::SelfLower])
2513 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2515 // Is `mut self` `n` tokens ahead?
2516 let is_isolated_mut_self =
2517 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2518 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2519 let parse_self_possibly_typed = |this: &mut Self, m| {
2520 let eself_ident = expect_self_ident(this);
2521 let eself_hi = this.prev_token.span;
2522 let eself = if this.eat(&token::Colon) {
2523 SelfKind::Explicit(this.parse_ty()?, m)
2527 Ok((eself, eself_ident, eself_hi))
2529 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2530 let recover_self_ptr = |this: &mut Self| {
2531 let msg = "cannot pass `self` by raw pointer";
2532 let span = this.token.span;
2533 this.struct_span_err(span, msg).span_label(span, msg).emit();
2535 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2538 // Parse optional `self` parameter of a method.
2539 // Only a limited set of initial token sequences is considered `self` parameters; anything
2540 // else is parsed as a normal function parameter list, so some lookahead is required.
2541 let eself_lo = self.token.span;
2542 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2543 token::BinOp(token::And) => {
2544 let eself = if is_isolated_self(self, 1) {
2547 SelfKind::Region(None, Mutability::Not)
2548 } else if is_isolated_mut_self(self, 1) {
2552 SelfKind::Region(None, Mutability::Mut)
2553 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2556 let lt = self.expect_lifetime();
2557 SelfKind::Region(Some(lt), Mutability::Not)
2558 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2561 let lt = self.expect_lifetime();
2563 SelfKind::Region(Some(lt), Mutability::Mut)
2568 (eself, expect_self_ident(self), self.prev_token.span)
2571 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2573 recover_self_ptr(self)?
2575 // `*mut self` and `*const self`
2576 token::BinOp(token::Star)
2577 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2581 recover_self_ptr(self)?
2583 // `self` and `self: TYPE`
2584 token::Ident(..) if is_isolated_self(self, 0) => {
2585 parse_self_possibly_typed(self, Mutability::Not)?
2587 // `mut self` and `mut self: TYPE`
2588 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2590 parse_self_possibly_typed(self, Mutability::Mut)?
2592 _ => return Ok(None),
2595 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2596 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2599 fn is_named_param(&self) -> bool {
2600 let offset = match &self.token.kind {
2601 token::Interpolated(nt) => match **nt {
2602 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2605 token::BinOp(token::And) | token::AndAnd => 1,
2606 _ if self.token.is_keyword(kw::Mut) => 1,
2610 self.look_ahead(offset, |t| t.is_ident())
2611 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2614 fn recover_first_param(&mut self) -> &'static str {
2616 .parse_outer_attributes()
2617 .and_then(|_| self.parse_self_param())
2618 .map_err(|e| e.cancel())
2620 Ok(Some(_)) => "method",
2626 enum IsMacroRulesItem {
2627 Yes { has_bang: bool },