1 use crate::errors::{DocCommentDoesNotDocumentAnything, UseEmptyBlockNotSemi};
3 use super::diagnostics::{dummy_arg, ConsumeClosingDelim};
4 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
5 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
9 use rustc_ast::token::{self, Delimiter, TokenKind};
10 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
11 use rustc_ast::{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::{MacArgs, 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;
25 use std::convert::TryFrom;
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();
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 let attrs = self.parse_outer_attributes()?;
102 self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
105 pub(super) fn parse_item_common(
110 fn_parse_mode: FnParseMode,
111 force_collect: ForceCollect,
112 ) -> PResult<'a, Option<Item>> {
113 // Don't use `maybe_whole` so that we have precise control
114 // over when we bump the parser
115 if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
116 let mut item = item.clone();
119 attrs.prepend_to_nt_inner(&mut item.attrs);
120 return Ok(Some(item.into_inner()));
123 let mut unclosed_delims = vec![];
125 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
127 this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
128 unclosed_delims.append(&mut this.unclosed_delims);
129 Ok((item?, TrailingToken::None))
132 self.unclosed_delims.append(&mut unclosed_delims);
136 fn parse_item_common_(
141 fn_parse_mode: FnParseMode,
142 ) -> PResult<'a, Option<Item>> {
143 let lo = self.token.span;
144 let vis = self.parse_visibility(FollowedByType::No)?;
145 let mut def = self.parse_defaultness();
147 self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, fn_parse_mode)?;
148 if let Some((ident, kind)) = kind {
149 self.error_on_unconsumed_default(def, &kind);
150 let span = lo.to(self.prev_token.span);
151 let id = DUMMY_NODE_ID;
152 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
153 return Ok(Some(item));
156 // At this point, we have failed to parse an item.
157 self.error_on_unmatched_vis(&vis);
158 self.error_on_unmatched_defaultness(def);
160 self.recover_attrs_no_item(&attrs)?;
165 /// Error in-case a non-inherited visibility was parsed but no item followed.
166 fn error_on_unmatched_vis(&self, vis: &Visibility) {
167 if let VisibilityKind::Inherited = vis.kind {
170 let vs = pprust::vis_to_string(&vis);
171 let vs = vs.trim_end();
172 self.struct_span_err(vis.span, &format!("visibility `{vs}` is not followed by an item"))
173 .span_label(vis.span, "the visibility")
174 .help(&format!("you likely meant to define an item, e.g., `{vs} fn foo() {{}}`"))
178 /// Error in-case a `default` was parsed but no item followed.
179 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
180 if let Defaultness::Default(sp) = def {
181 self.struct_span_err(sp, "`default` is not followed by an item")
182 .span_label(sp, "the `default` qualifier")
183 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
188 /// Error in-case `default` was parsed in an in-appropriate context.
189 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
190 if let Defaultness::Default(span) = def {
191 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
192 self.struct_span_err(span, &msg)
193 .span_label(span, "`default` because of this")
194 .note("only associated `fn`, `const`, and `type` items can be `default`")
199 /// Parses one of the items allowed by the flags.
203 macros_allowed: bool,
206 def: &mut Defaultness,
207 fn_parse_mode: FnParseMode,
208 ) -> PResult<'a, Option<ItemInfo>> {
209 let def_final = def == &Defaultness::Final;
210 let mut def = || mem::replace(def, Defaultness::Final);
212 let info = if self.eat_keyword(kw::Use) {
213 self.parse_use_item()?
214 } else if self.check_fn_front_matter(def_final) {
216 let (ident, sig, generics, body) = self.parse_fn(attrs, fn_parse_mode, lo, vis)?;
217 (ident, ItemKind::Fn(Box::new(Fn { defaultness: def(), sig, generics, body })))
218 } else if self.eat_keyword(kw::Extern) {
219 if self.eat_keyword(kw::Crate) {
221 self.parse_item_extern_crate()?
224 self.parse_item_foreign_mod(attrs, Unsafe::No)?
226 } else if self.is_unsafe_foreign_mod() {
228 let unsafety = self.parse_unsafety();
229 self.expect_keyword(kw::Extern)?;
230 self.parse_item_foreign_mod(attrs, unsafety)?
231 } else if self.is_static_global() {
233 self.bump(); // `static`
234 let m = self.parse_mutability();
235 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
236 (ident, ItemKind::Static(ty, m, expr))
237 } else if let Const::Yes(const_span) = self.parse_constness() {
239 if self.token.is_keyword(kw::Impl) {
240 // recover from `const impl`, suggest `impl const`
241 self.recover_const_impl(const_span, attrs, def())?
243 self.recover_const_mut(const_span);
244 let (ident, ty, expr) = self.parse_item_global(None)?;
245 (ident, ItemKind::Const(def(), ty, expr))
247 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
249 self.parse_item_trait(attrs, lo)?
250 } else if self.check_keyword(kw::Impl)
251 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
254 self.parse_item_impl(attrs, def())?
255 } else if self.check_keyword(kw::Mod)
256 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
259 self.parse_item_mod(attrs)?
260 } else if self.eat_keyword(kw::Type) {
262 self.parse_type_alias(def())?
263 } else if self.eat_keyword(kw::Enum) {
265 self.parse_item_enum()?
266 } else if self.eat_keyword(kw::Struct) {
268 self.parse_item_struct()?
269 } else if self.is_kw_followed_by_ident(kw::Union) {
271 self.bump(); // `union`
272 self.parse_item_union()?
273 } else if self.eat_keyword(kw::Macro) {
275 self.parse_item_decl_macro(lo)?
276 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
278 self.parse_item_macro_rules(vis, has_bang)?
279 } else if self.isnt_macro_invocation()
280 && (self.token.is_ident_named(sym::import)
281 || self.token.is_ident_named(sym::using)
282 || self.token.is_ident_named(sym::include)
283 || self.token.is_ident_named(sym::require))
285 return self.recover_import_as_use();
286 } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
287 self.recover_missing_kw_before_item()?;
289 } else if macros_allowed && self.check_path() {
290 // MACRO INVOCATION ITEM
291 (Ident::empty(), ItemKind::MacCall(P(self.parse_item_macro(vis)?)))
298 fn recover_import_as_use(&mut self) -> PResult<'a, Option<(Ident, ItemKind)>> {
299 let span = self.token.span;
300 let token_name = super::token_descr(&self.token);
301 let snapshot = self.create_snapshot_for_diagnostic();
303 match self.parse_use_item() {
305 self.struct_span_err(span, format!("expected item, found {token_name}"))
306 .span_suggestion_short(
308 "items are imported using the `use` keyword",
310 Applicability::MachineApplicable,
317 self.restore_snapshot(snapshot);
323 fn parse_use_item(&mut self) -> PResult<'a, (Ident, ItemKind)> {
324 let tree = self.parse_use_tree()?;
325 if let Err(mut e) = self.expect_semi() {
327 UseTreeKind::Glob => {
328 e.note("the wildcard token must be last on the path");
330 UseTreeKind::Nested(..) => {
331 e.note("glob-like brace syntax must be last on the path");
337 Ok((Ident::empty(), ItemKind::Use(tree)))
340 /// When parsing a statement, would the start of a path be an item?
341 pub(super) fn is_path_start_item(&mut self) -> bool {
342 self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
343 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
344 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
345 || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
348 /// Are we sure this could not possibly be a macro invocation?
349 fn isnt_macro_invocation(&mut self) -> bool {
350 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
353 /// Recover on encountering a struct or method definition where the user
354 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
355 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
356 // Space between `pub` keyword and the identifier
359 // ^^^ `sp` points here
360 let sp = self.prev_token.span.between(self.token.span);
361 let full_sp = self.prev_token.span.to(self.token.span);
362 let ident_sp = self.token.span;
363 if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace)) {
364 // possible public struct definition where `struct` was forgotten
365 let ident = self.parse_ident().unwrap();
366 let msg = format!("add `struct` here to parse `{ident}` as a public struct");
367 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
368 err.span_suggestion_short(
372 Applicability::MaybeIncorrect, // speculative
375 } else if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Parenthesis)) {
376 let ident = self.parse_ident().unwrap();
378 let kw_name = self.recover_first_param();
379 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::Yes);
380 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
381 self.eat_to_tokens(&[&token::OpenDelim(Delimiter::Brace)]);
383 ("fn", kw_name, false)
384 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
386 ("fn", kw_name, false)
387 } else if self.check(&token::Colon) {
391 ("fn` or `struct", "function or struct", true)
394 let msg = format!("missing `{kw}` for {kw_name} definition");
395 let mut err = self.struct_span_err(sp, &msg);
397 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
399 format!("add `{kw}` here to parse `{ident}` as a public {kw_name}");
400 err.span_suggestion_short(
404 Applicability::MachineApplicable,
406 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
409 "if you meant to call a macro, try",
410 format!("{}!", snippet),
411 // this is the `ambiguous` conditional branch
412 Applicability::MaybeIncorrect,
416 "if you meant to call a macro, remove the `pub` \
417 and add a trailing `!` after the identifier",
421 } else if self.look_ahead(1, |t| *t == token::Lt) {
422 let ident = self.parse_ident().unwrap();
423 self.eat_to_tokens(&[&token::Gt]);
425 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(Delimiter::Parenthesis)) {
426 ("fn", self.recover_first_param(), false)
427 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
428 ("struct", "struct", false)
430 ("fn` or `struct", "function or struct", true)
432 let msg = format!("missing `{kw}` for {kw_name} definition");
433 let mut err = self.struct_span_err(sp, &msg);
435 err.span_suggestion_short(
437 &format!("add `{kw}` here to parse `{ident}` as a public {kw_name}"),
439 Applicability::MachineApplicable,
448 /// Parses an item macro, e.g., `item!();`.
449 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
450 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
451 self.expect(&token::Not)?; // `!`
452 match self.parse_mac_args() {
453 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
455 self.eat_semi_for_macro_if_needed(&args);
456 self.complain_if_pub_macro(vis, false);
457 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
461 // Maybe the user misspelled `macro_rules` (issue #91227)
462 if self.token.is_ident()
463 && path.segments.len() == 1
464 && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
468 "perhaps you meant to define a macro",
470 Applicability::MachineApplicable,
478 /// Recover if we parsed attributes and expected an item but there was none.
479 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
480 let ([start @ end] | [start, .., end]) = attrs else {
483 let msg = if end.is_doc_comment() {
484 "expected item after doc comment"
486 "expected item after attributes"
488 let mut err = self.struct_span_err(end.span, msg);
489 if end.is_doc_comment() {
490 err.span_label(end.span, "this doc comment doesn't document anything");
492 if end.meta_kind().is_some() {
493 if self.token.kind == TokenKind::Semi {
494 err.span_suggestion_verbose(
496 "consider removing this semicolon",
498 Applicability::MaybeIncorrect,
502 if let [.., penultimate, _] = attrs {
503 err.span_label(start.span.to(penultimate.span), "other attributes here");
508 fn is_async_fn(&self) -> bool {
509 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
512 fn parse_polarity(&mut self) -> ast::ImplPolarity {
513 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
514 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
516 ast::ImplPolarity::Negative(self.prev_token.span)
518 ast::ImplPolarity::Positive
522 /// Parses an implementation item.
524 /// ```ignore (illustrative)
525 /// impl<'a, T> TYPE { /* impl items */ }
526 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
527 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
528 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
531 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
533 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
534 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
539 defaultness: Defaultness,
540 ) -> PResult<'a, ItemInfo> {
541 let unsafety = self.parse_unsafety();
542 self.expect_keyword(kw::Impl)?;
544 // First, parse generic parameters if necessary.
545 let mut generics = if self.choose_generics_over_qpath(0) {
546 self.parse_generics()?
548 let mut generics = Generics::default();
550 // /\ this is where `generics.span` should point when there are no type params.
551 generics.span = self.prev_token.span.shrink_to_hi();
555 let constness = self.parse_constness();
556 if let Const::Yes(span) = constness {
557 self.sess.gated_spans.gate(sym::const_trait_impl, span);
560 let polarity = self.parse_polarity();
562 // Parse both types and traits as a type, then reinterpret if necessary.
563 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
564 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
566 let span = self.prev_token.span.between(self.token.span);
567 self.struct_span_err(span, "missing trait in a trait impl")
572 Applicability::HasPlaceholders,
575 span.to(self.token.span),
576 "for an inherent impl, drop this `for`",
578 Applicability::MaybeIncorrect,
582 kind: TyKind::Path(None, err_path(span)),
588 self.parse_ty_with_generics_recovery(&generics)?
591 // If `for` is missing we try to recover.
592 let has_for = self.eat_keyword(kw::For);
593 let missing_for_span = self.prev_token.span.between(self.token.span);
595 let ty_second = if self.token == token::DotDot {
596 // We need to report this error after `cfg` expansion for compatibility reasons
597 self.bump(); // `..`, do not add it to expected tokens
598 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
599 } else if has_for || self.token.can_begin_type() {
600 Some(self.parse_ty()?)
605 generics.where_clause = self.parse_where_clause()?;
607 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
609 let item_kind = match ty_second {
611 // impl Trait for Type
613 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
614 .span_suggestion_short(
618 Applicability::MachineApplicable,
623 let ty_first = ty_first.into_inner();
624 let path = match ty_first.kind {
625 // This notably includes paths passed through `ty` macro fragments (#46438).
626 TyKind::Path(None, path) => path,
628 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
629 err_path(ty_first.span)
632 let trait_ref = TraitRef { path, ref_id: ty_first.id };
634 ItemKind::Impl(Box::new(Impl {
640 of_trait: Some(trait_ref),
647 ItemKind::Impl(Box::new(Impl {
660 Ok((Ident::empty(), item_kind))
663 fn parse_item_list<T>(
666 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
667 ) -> PResult<'a, Vec<T>> {
668 let open_brace_span = self.token.span;
670 // Recover `impl Ty;` instead of `impl Ty {}`
671 if self.token == TokenKind::Semi {
672 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
677 self.expect(&token::OpenDelim(Delimiter::Brace))?;
678 attrs.extend(self.parse_inner_attributes()?);
680 let mut items = Vec::new();
681 while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
682 if self.recover_doc_comment_before_brace() {
685 match parse_item(self) {
687 let is_unnecessary_semicolon = !items.is_empty()
688 // When the close delim is `)` in a case like the following, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
689 // but the actual `token.kind` is `token::CloseDelim(Delimiter::Bracket)`.
690 // This is because the `token.kind` of the close delim is treated as the same as
691 // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
692 // Therefore, `token.kind` should not be compared here.
697 // fn qux() -> Option<usize> {
700 // ^ this close delim
705 .span_to_snippet(self.prev_token.span)
706 .map_or(false, |snippet| snippet == "}")
707 && self.token.kind == token::Semi;
708 let semicolon_span = self.token.span;
709 // We have to bail or we'll potentially never make progress.
710 let non_item_span = self.token.span;
711 let is_let = self.token.is_keyword(kw::Let);
713 let mut err = self.struct_span_err(non_item_span, "non-item in item list");
714 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
718 "consider using `const` instead of `let` for associated const",
720 Applicability::MachineApplicable,
723 err.span_label(open_brace_span, "item list starts here")
724 .span_label(non_item_span, "non-item starts here")
725 .span_label(self.prev_token.span, "item list ends here");
727 if is_unnecessary_semicolon {
730 "consider removing this semicolon",
732 Applicability::MaybeIncorrect,
738 Ok(Some(item)) => items.extend(item),
740 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
741 err.span_label(open_brace_span, "while parsing this item list starting here")
742 .span_label(self.prev_token.span, "the item list ends here")
751 /// Recover on a doc comment before `}`.
752 fn recover_doc_comment_before_brace(&mut self) -> bool {
753 if let token::DocComment(..) = self.token.kind {
754 if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
759 "found a documentation comment that doesn't document anything",
761 .span_label(self.token.span, "this doc comment doesn't document anything")
763 "doc comments must come before what they document, if a comment was \
774 /// Parses defaultness (i.e., `default` or nothing).
775 fn parse_defaultness(&mut self) -> Defaultness {
776 // We are interested in `default` followed by another identifier.
777 // However, we must avoid keywords that occur as binary operators.
778 // Currently, the only applicable keyword is `as` (`default as Ty`).
779 if self.check_keyword(kw::Default)
780 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
782 self.bump(); // `default`
783 Defaultness::Default(self.prev_token.uninterpolated_span())
789 /// Is this an `(unsafe auto? | auto) trait` item?
790 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
792 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
794 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
797 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
798 fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
799 let unsafety = self.parse_unsafety();
800 // Parse optional `auto` prefix.
801 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
803 self.expect_keyword(kw::Trait)?;
804 let ident = self.parse_ident()?;
805 let mut generics = self.parse_generics()?;
807 // Parse optional colon and supertrait bounds.
808 let had_colon = self.eat(&token::Colon);
809 let span_at_colon = self.prev_token.span;
810 let bounds = if had_colon {
811 self.parse_generic_bounds(Some(self.prev_token.span))?
816 let span_before_eq = self.prev_token.span;
817 if self.eat(&token::Eq) {
818 // It's a trait alias.
820 let span = span_at_colon.to(span_before_eq);
821 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
824 let bounds = self.parse_generic_bounds(None)?;
825 generics.where_clause = self.parse_where_clause()?;
828 let whole_span = lo.to(self.prev_token.span);
829 if is_auto == IsAuto::Yes {
830 let msg = "trait aliases cannot be `auto`";
831 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
833 if let Unsafe::Yes(_) = unsafety {
834 let msg = "trait aliases cannot be `unsafe`";
835 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
838 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
840 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
842 // It's a normal trait.
843 generics.where_clause = self.parse_where_clause()?;
844 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
847 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
852 pub fn parse_impl_item(
854 force_collect: ForceCollect,
855 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
856 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
857 self.parse_assoc_item(fn_parse_mode, force_collect)
860 pub fn parse_trait_item(
862 force_collect: ForceCollect,
863 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
865 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
866 self.parse_assoc_item(fn_parse_mode, force_collect)
869 /// Parses associated items.
872 fn_parse_mode: FnParseMode,
873 force_collect: ForceCollect,
874 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
875 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
876 |Item { attrs, id, span, vis, ident, kind, tokens }| {
877 let kind = match AssocItemKind::try_from(kind) {
879 Err(kind) => match kind {
880 ItemKind::Static(a, _, b) => {
881 self.struct_span_err(span, "associated `static` items are not allowed")
883 AssocItemKind::Const(Defaultness::Final, a, b)
885 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
888 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
893 /// Parses a `type` alias with the following grammar:
895 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
897 /// The `"type"` has already been eaten.
898 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
899 let ident = self.parse_ident()?;
900 let mut generics = self.parse_generics()?;
902 // Parse optional colon and param bounds.
904 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
905 let before_where_clause = self.parse_where_clause()?;
907 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
909 let after_where_clause = self.parse_where_clause()?;
911 let where_clauses = (
912 TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
913 TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
915 let where_predicates_split = before_where_clause.predicates.len();
916 let mut predicates = before_where_clause.predicates;
917 predicates.extend(after_where_clause.predicates.into_iter());
918 let where_clause = WhereClause {
919 has_where_token: before_where_clause.has_where_token
920 || after_where_clause.has_where_token,
924 generics.where_clause = where_clause;
930 ItemKind::TyAlias(Box::new(TyAlias {
934 where_predicates_split,
941 /// Parses a `UseTree`.
944 /// USE_TREE = [`::`] `*` |
945 /// [`::`] `{` USE_TREE_LIST `}` |
947 /// PATH `::` `{` USE_TREE_LIST `}` |
948 /// PATH [`as` IDENT]
950 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
951 let lo = self.token.span;
953 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
954 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
955 || self.check(&token::BinOp(token::Star))
956 || self.is_import_coupler()
958 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
959 let mod_sep_ctxt = self.token.span.ctxt();
960 if self.eat(&token::ModSep) {
963 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
966 self.parse_use_tree_glob_or_nested()?
968 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
969 prefix = self.parse_path(PathStyle::Mod)?;
971 if self.eat(&token::ModSep) {
972 self.parse_use_tree_glob_or_nested()?
974 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
978 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
981 /// Parses `*` or `{...}`.
982 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
983 Ok(if self.eat(&token::BinOp(token::Star)) {
986 UseTreeKind::Nested(self.parse_use_tree_list()?)
990 /// Parses a `UseTreeKind::Nested(list)`.
993 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
995 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
996 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
1000 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1001 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1004 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1005 match self.token.ident() {
1006 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1010 _ => self.parse_ident(),
1014 /// Parses `extern crate` links.
1018 /// ```ignore (illustrative)
1019 /// extern crate foo;
1020 /// extern crate bar as foo;
1022 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1023 // Accept `extern crate name-like-this` for better diagnostics
1024 let orig_name = self.parse_crate_name_with_dashes()?;
1025 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1026 (rename, Some(orig_name.name))
1030 self.expect_semi()?;
1031 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1034 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1035 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1036 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1038 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1039 self.parse_path_segment_ident()
1043 let mut idents = vec![];
1044 let mut replacement = vec![];
1045 let mut fixed_crate_name = false;
1046 // Accept `extern crate name-like-this` for better diagnostics.
1047 let dash = token::BinOp(token::BinOpToken::Minus);
1048 if self.token == dash {
1049 // Do not include `-` as part of the expected tokens list.
1050 while self.eat(&dash) {
1051 fixed_crate_name = true;
1052 replacement.push((self.prev_token.span, "_".to_string()));
1053 idents.push(self.parse_ident()?);
1056 if fixed_crate_name {
1057 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1058 let mut fixed_name = ident.name.to_string();
1059 for part in idents {
1060 fixed_name.push_str(&format!("_{}", part.name));
1062 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1064 self.struct_span_err(fixed_name_sp, error_msg)
1065 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1066 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1072 /// Parses `extern` for foreign ABIs modules.
1074 /// `extern` is expected to have been consumed before calling this method.
1078 /// ```ignore (only-for-syntax-highlight)
1082 fn parse_item_foreign_mod(
1084 attrs: &mut AttrVec,
1085 mut unsafety: Unsafe,
1086 ) -> PResult<'a, ItemInfo> {
1087 let abi = self.parse_abi(); // ABI?
1088 if unsafety == Unsafe::No
1089 && self.token.is_keyword(kw::Unsafe)
1090 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1092 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1094 unsafety = Unsafe::Yes(self.token.span);
1095 self.eat_keyword(kw::Unsafe);
1097 let module = ast::ForeignMod {
1100 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1102 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1105 /// Parses a foreign item (one in an `extern { ... }` block).
1106 pub fn parse_foreign_item(
1108 force_collect: ForceCollect,
1109 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1110 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1111 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1112 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1113 let kind = match ForeignItemKind::try_from(kind) {
1115 Err(kind) => match kind {
1116 ItemKind::Const(_, a, b) => {
1117 self.error_on_foreign_const(span, ident);
1118 ForeignItemKind::Static(a, Mutability::Not, b)
1120 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1123 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1128 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1129 let span = self.sess.source_map().guess_head_span(span);
1130 let descr = kind.descr();
1131 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1132 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1137 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1138 self.struct_span_err(ident.span, "extern items cannot be `const`")
1140 span.with_hi(ident.span.lo()),
1141 "try using a static value",
1143 Applicability::MachineApplicable,
1145 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1149 fn is_unsafe_foreign_mod(&self) -> bool {
1150 self.token.is_keyword(kw::Unsafe)
1151 && self.is_keyword_ahead(1, &[kw::Extern])
1153 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1154 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1158 fn is_static_global(&mut self) -> bool {
1159 if self.check_keyword(kw::Static) {
1160 // Check if this could be a closure.
1161 !self.look_ahead(1, |token| {
1162 if token.is_keyword(kw::Move) {
1165 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1172 /// Recover on `const mut` with `const` already eaten.
1173 fn recover_const_mut(&mut self, const_span: Span) {
1174 if self.eat_keyword(kw::Mut) {
1175 let span = self.prev_token.span;
1176 self.struct_span_err(span, "const globals cannot be mutable")
1177 .span_label(span, "cannot be mutable")
1180 "you might want to declare a static instead",
1182 Applicability::MaybeIncorrect,
1185 } else if self.eat_keyword(kw::Let) {
1186 let span = self.prev_token.span;
1187 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1189 const_span.to(span),
1192 Applicability::MaybeIncorrect,
1198 /// Recover on `const impl` with `const` already eaten.
1199 fn recover_const_impl(
1202 attrs: &mut AttrVec,
1203 defaultness: Defaultness,
1204 ) -> PResult<'a, ItemInfo> {
1205 let impl_span = self.token.span;
1206 let mut err = self.expected_ident_found();
1208 // Only try to recover if this is implementing a trait for a type
1209 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1210 Ok(impl_info) => impl_info,
1211 Err(recovery_error) => {
1212 // Recovery failed, raise the "expected identifier" error
1213 recovery_error.cancel();
1219 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1220 *constness = Const::Yes(const_span);
1222 let before_trait = trai.path.span.shrink_to_lo();
1223 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1224 err.multipart_suggestion(
1225 "you might have meant to write a const trait impl",
1226 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1227 Applicability::MaybeIncorrect,
1231 ItemKind::Impl { .. } => return Err(err),
1232 _ => unreachable!(),
1238 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1239 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1241 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1242 fn parse_item_global(
1244 m: Option<Mutability>,
1245 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1246 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1248 // Parse the type of a `const` or `static mut?` item.
1249 // That is, the `":" $ty` fragment.
1250 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1252 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1253 (true, false) => self.parse_ty()?,
1254 (colon, _) => self.recover_missing_const_type(colon, m),
1257 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1258 self.expect_semi()?;
1262 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1263 /// This means that the type is missing.
1264 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1265 // Construct the error and stash it away with the hope
1266 // that typeck will later enrich the error with a type.
1267 let kind = match m {
1268 Some(Mutability::Mut) => "static mut",
1269 Some(Mutability::Not) => "static",
1273 let colon = match colon_present {
1278 let span = self.prev_token.span.shrink_to_hi();
1279 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1280 err.span_suggestion(
1282 "provide a type for the item",
1283 format!("{colon} <type>"),
1284 Applicability::HasPlaceholders,
1286 err.stash(span, StashKey::ItemNoType);
1288 // The user intended that the type be inferred,
1289 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1290 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1293 /// Parses an enum declaration.
1294 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1295 if self.token.is_keyword(kw::Struct) {
1296 let span = self.prev_token.span.to(self.token.span);
1297 let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1298 err.span_suggestion(
1300 "replace `enum struct` with",
1302 Applicability::MachineApplicable,
1304 if self.look_ahead(1, |t| t.is_ident()) {
1312 let id = self.parse_ident()?;
1313 let mut generics = self.parse_generics()?;
1314 generics.where_clause = self.parse_where_clause()?;
1316 // Possibly recover `enum Foo;` instead of `enum Foo {}`
1317 let (variants, _) = if self.token == TokenKind::Semi {
1318 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1322 self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1324 e.span_label(id.span, "while parsing this enum");
1325 self.recover_stmt();
1331 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1332 Ok((id, ItemKind::Enum(enum_definition, generics)))
1335 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1336 let variant_attrs = self.parse_outer_attributes()?;
1337 self.collect_tokens_trailing_token(
1340 |this, variant_attrs| {
1341 let vlo = this.token.span;
1343 let vis = this.parse_visibility(FollowedByType::No)?;
1344 if !this.recover_nested_adt_item(kw::Enum)? {
1345 return Ok((None, TrailingToken::None));
1347 let ident = this.parse_field_ident("enum", vlo)?;
1349 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1350 // Parse a struct variant.
1351 let (fields, recovered) =
1352 this.parse_record_struct_body("struct", ident.span, false)?;
1353 VariantData::Struct(fields, recovered)
1354 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1355 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1357 VariantData::Unit(DUMMY_NODE_ID)
1361 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1363 let vr = ast::Variant {
1367 attrs: variant_attrs,
1370 span: vlo.to(this.prev_token.span),
1371 is_placeholder: false,
1374 Ok((Some(vr), TrailingToken::MaybeComma))
1379 /// Parses `struct Foo { ... }`.
1380 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1381 let class_name = self.parse_ident()?;
1383 let mut generics = self.parse_generics()?;
1385 // There is a special case worth noting here, as reported in issue #17904.
1386 // If we are parsing a tuple struct it is the case that the where clause
1387 // should follow the field list. Like so:
1389 // struct Foo<T>(T) where T: Copy;
1391 // If we are parsing a normal record-style struct it is the case
1392 // that the where clause comes before the body, and after the generics.
1393 // So if we look ahead and see a brace or a where-clause we begin
1394 // parsing a record style struct.
1396 // Otherwise if we look ahead and see a paren we parse a tuple-style
1399 let vdata = if self.token.is_keyword(kw::Where) {
1400 generics.where_clause = self.parse_where_clause()?;
1401 if self.eat(&token::Semi) {
1402 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1403 VariantData::Unit(DUMMY_NODE_ID)
1405 // If we see: `struct Foo<T> where T: Copy { ... }`
1406 let (fields, recovered) = self.parse_record_struct_body(
1409 generics.where_clause.has_where_token,
1411 VariantData::Struct(fields, recovered)
1413 // No `where` so: `struct Foo<T>;`
1414 } else if self.eat(&token::Semi) {
1415 VariantData::Unit(DUMMY_NODE_ID)
1416 // Record-style struct definition
1417 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1418 let (fields, recovered) = self.parse_record_struct_body(
1421 generics.where_clause.has_where_token,
1423 VariantData::Struct(fields, recovered)
1424 // Tuple-style struct definition with optional where-clause.
1425 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1426 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1427 generics.where_clause = self.parse_where_clause()?;
1428 self.expect_semi()?;
1431 let token_str = super::token_descr(&self.token);
1433 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1435 let mut err = self.struct_span_err(self.token.span, msg);
1436 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1440 Ok((class_name, ItemKind::Struct(vdata, generics)))
1443 /// Parses `union Foo { ... }`.
1444 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1445 let class_name = self.parse_ident()?;
1447 let mut generics = self.parse_generics()?;
1449 let vdata = if self.token.is_keyword(kw::Where) {
1450 generics.where_clause = self.parse_where_clause()?;
1451 let (fields, recovered) = self.parse_record_struct_body(
1454 generics.where_clause.has_where_token,
1456 VariantData::Struct(fields, recovered)
1457 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1458 let (fields, recovered) = self.parse_record_struct_body(
1461 generics.where_clause.has_where_token,
1463 VariantData::Struct(fields, recovered)
1465 let token_str = super::token_descr(&self.token);
1466 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1467 let mut err = self.struct_span_err(self.token.span, msg);
1468 err.span_label(self.token.span, "expected `where` or `{` after union name");
1472 Ok((class_name, ItemKind::Union(vdata, generics)))
1475 fn parse_record_struct_body(
1480 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1481 let mut fields = Vec::new();
1482 let mut recovered = false;
1483 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1484 while self.token != token::CloseDelim(Delimiter::Brace) {
1485 let field = self.parse_field_def(adt_ty).map_err(|e| {
1486 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1491 Ok(field) => fields.push(field),
1493 err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1499 self.eat(&token::CloseDelim(Delimiter::Brace));
1501 let token_str = super::token_descr(&self.token);
1503 "expected {}`{{` after struct name, found {}",
1504 if parsed_where { "" } else { "`where`, or " },
1507 let mut err = self.struct_span_err(self.token.span, msg);
1511 "expected {}`{{` after struct name",
1512 if parsed_where { "" } else { "`where`, or " }
1518 Ok((fields, recovered))
1521 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1522 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1523 // Unit like structs are handled in parse_item_struct function
1524 self.parse_paren_comma_seq(|p| {
1525 let attrs = p.parse_outer_attributes()?;
1526 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1527 let lo = p.token.span;
1528 let vis = p.parse_visibility(FollowedByType::Yes)?;
1529 let ty = p.parse_ty()?;
1533 span: lo.to(ty.span),
1539 is_placeholder: false,
1541 TrailingToken::MaybeComma,
1548 /// Parses an element of a struct declaration.
1549 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1550 let attrs = self.parse_outer_attributes()?;
1551 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1552 let lo = this.token.span;
1553 let vis = this.parse_visibility(FollowedByType::No)?;
1554 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1558 /// Parses a structure field declaration.
1559 fn parse_single_struct_field(
1565 ) -> PResult<'a, FieldDef> {
1566 let mut seen_comma: bool = false;
1567 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1568 if self.token == token::Comma {
1571 if self.eat(&token::Semi) {
1572 let sp = self.prev_token.span;
1573 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1574 err.span_suggestion_short(
1576 "replace `;` with `,`",
1578 Applicability::MachineApplicable,
1582 match self.token.kind {
1586 token::CloseDelim(Delimiter::Brace) => {}
1587 token::DocComment(..) => {
1588 let previous_span = self.prev_token.span;
1589 let mut err = DocCommentDoesNotDocumentAnything {
1590 span: self.token.span,
1591 missing_comma: None,
1593 self.bump(); // consume the doc comment
1594 let comma_after_doc_seen = self.eat(&token::Comma);
1595 // `seen_comma` is always false, because we are inside doc block
1596 // condition is here to make code more readable
1597 if !seen_comma && comma_after_doc_seen {
1600 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1601 self.sess.emit_err(err);
1604 let sp = previous_span.shrink_to_hi();
1605 err.missing_comma = Some(sp);
1607 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1611 let sp = self.prev_token.span.shrink_to_hi();
1612 let mut err = self.struct_span_err(
1614 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1617 // Try to recover extra trailing angle brackets
1618 let mut recovered = false;
1619 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1620 if let Some(last_segment) = segments.last() {
1621 recovered = self.check_trailing_angle_brackets(
1623 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1626 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1628 self.eat(&token::Comma);
1629 // `check_trailing_angle_brackets` already emitted a nicer error
1630 // NOTE(eddyb) this was `.cancel()`, but `err`
1631 // gets returned, so we can't fully defuse it.
1637 if self.token.is_ident()
1638 || (self.token.kind == TokenKind::Pound
1639 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1641 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1642 // emit the diagnostic and keep going
1643 err.span_suggestion(
1645 "try adding a comma",
1647 Applicability::MachineApplicable,
1654 // Make sure an error was emitted (either by recovering an angle bracket,
1655 // or by finding an identifier as the next token), since we're
1656 // going to continue parsing
1657 assert!(self.sess.span_diagnostic.has_errors().is_some());
1666 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1667 if let Err(mut err) = self.expect(&token::Colon) {
1668 let sm = self.sess.source_map();
1669 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1670 let semi_typo = self.token.kind == token::Semi
1671 && self.look_ahead(1, |t| {
1673 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1674 // when there's no type and `;` was used instead of a comma.
1675 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1676 (Ok(l), Ok(r)) => l.line == r.line,
1680 if eq_typo || semi_typo {
1682 // Gracefully handle small typos.
1683 err.span_suggestion_short(
1684 self.prev_token.span,
1685 "field names and their types are separated with `:`",
1687 Applicability::MachineApplicable,
1697 /// Parses a structure field.
1698 fn parse_name_and_ty(
1704 ) -> PResult<'a, FieldDef> {
1705 let name = self.parse_field_ident(adt_ty, lo)?;
1706 self.expect_field_ty_separator()?;
1707 let ty = self.parse_ty()?;
1708 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1709 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1710 .span_suggestion_verbose(
1712 "write a path separator here",
1714 Applicability::MaybeIncorrect,
1718 if self.token.kind == token::Eq {
1720 let const_expr = self.parse_anon_const_expr()?;
1721 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1722 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1725 "remove this unsupported default value",
1727 Applicability::MachineApplicable,
1732 span: lo.to(self.prev_token.span),
1738 is_placeholder: false,
1742 /// Parses a field identifier. Specialized version of `parse_ident_common`
1743 /// for better diagnostics and suggestions.
1744 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1745 let (ident, is_raw) = self.ident_or_err()?;
1746 if !is_raw && ident.is_reserved() {
1747 let snapshot = self.create_snapshot_for_diagnostic();
1748 let err = if self.check_fn_front_matter(false) {
1749 let inherited_vis = Visibility {
1750 span: rustc_span::DUMMY_SP,
1751 kind: VisibilityKind::Inherited,
1754 // We use `parse_fn` to get a span for the function
1755 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1756 match self.parse_fn(&mut AttrVec::new(), fn_parse_mode, lo, &inherited_vis) {
1758 let mut err = self.struct_span_err(
1759 lo.to(self.prev_token.span),
1760 &format!("functions are not allowed in {adt_ty} definitions"),
1763 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1765 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1770 self.restore_snapshot(snapshot);
1771 self.expected_ident_found()
1774 } else if self.eat_keyword(kw::Struct) {
1775 match self.parse_item_struct() {
1777 let mut err = self.struct_span_err(
1778 lo.with_hi(ident.span.hi()),
1779 &format!("structs are not allowed in {adt_ty} definitions"),
1781 err.help("consider creating a new `struct` definition instead of nesting");
1786 self.restore_snapshot(snapshot);
1787 self.expected_ident_found()
1791 let mut err = self.expected_ident_found();
1792 if self.eat_keyword_noexpect(kw::Let)
1793 && let removal_span = self.prev_token.span.until(self.token.span)
1794 && let Ok(ident) = self.parse_ident_common(false)
1795 // Cancel this error, we don't need it.
1796 .map_err(|err| err.cancel())
1797 && self.token.kind == TokenKind::Colon
1799 err.span_suggestion(
1801 "remove this `let` keyword",
1803 Applicability::MachineApplicable,
1805 err.note("the `let` keyword is not allowed in `struct` fields");
1806 err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1810 self.restore_snapshot(snapshot);
1820 /// Parses a declarative macro 2.0 definition.
1821 /// The `macro` keyword has already been parsed.
1823 /// MacBody = "{" TOKEN_STREAM "}" ;
1824 /// MacParams = "(" TOKEN_STREAM ")" ;
1825 /// DeclMac = "macro" Ident MacParams? MacBody ;
1827 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1828 let ident = self.parse_ident()?;
1829 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1830 self.parse_mac_args()? // `MacBody`
1831 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1832 let params = self.parse_token_tree(); // `MacParams`
1833 let pspan = params.span();
1834 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1835 return self.unexpected();
1837 let body = self.parse_token_tree(); // `MacBody`
1838 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1839 let bspan = body.span();
1840 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1841 let tokens = TokenStream::new(vec![params, arrow, body]);
1842 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1843 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1845 return self.unexpected();
1848 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1849 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1852 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1853 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1854 if self.check_keyword(kw::MacroRules) {
1855 let macro_rules_span = self.token.span;
1857 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1858 return IsMacroRulesItem::Yes { has_bang: true };
1859 } else if self.look_ahead(1, |t| (t.is_ident())) {
1861 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1866 Applicability::MachineApplicable,
1870 return IsMacroRulesItem::Yes { has_bang: false };
1874 IsMacroRulesItem::No
1877 /// Parses a `macro_rules! foo { ... }` declarative macro.
1878 fn parse_item_macro_rules(
1882 ) -> PResult<'a, ItemInfo> {
1883 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1886 self.expect(&token::Not)?; // `!`
1888 let ident = self.parse_ident()?;
1890 if self.eat(&token::Not) {
1891 // Handle macro_rules! foo!
1892 let span = self.prev_token.span;
1893 self.struct_span_err(span, "macro names aren't followed by a `!`")
1894 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1898 let body = self.parse_mac_args()?;
1899 self.eat_semi_for_macro_if_needed(&body);
1900 self.complain_if_pub_macro(vis, true);
1902 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1905 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1906 /// If that's not the case, emit an error.
1907 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1908 if let VisibilityKind::Inherited = vis.kind {
1912 let vstr = pprust::vis_to_string(vis);
1913 let vstr = vstr.trim_end();
1915 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1916 self.struct_span_err(vis.span, &msg)
1919 "try exporting the macro",
1921 Applicability::MaybeIncorrect, // speculative
1925 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1928 "remove the visibility",
1930 Applicability::MachineApplicable,
1932 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1937 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1938 if args.need_semicolon() && !self.eat(&token::Semi) {
1939 self.report_invalid_macro_expansion_item(args);
1943 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1944 let span = args.span().expect("undelimited macro call");
1945 let mut err = self.struct_span_err(
1947 "macros that expand to items must be delimited with braces or followed by a semicolon",
1949 // FIXME: This will make us not emit the help even for declarative
1950 // macros within the same crate (that we can fix), which is sad.
1951 if !span.from_expansion() {
1952 if self.unclosed_delims.is_empty() {
1953 let DelimSpan { open, close } = match args {
1954 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1955 MacArgs::Delimited(dspan, ..) => *dspan,
1957 err.multipart_suggestion(
1958 "change the delimiters to curly braces",
1959 vec![(open, "{".to_string()), (close, '}'.to_string())],
1960 Applicability::MaybeIncorrect,
1963 err.span_suggestion(
1965 "change the delimiters to curly braces",
1967 Applicability::HasPlaceholders,
1970 err.span_suggestion(
1971 span.shrink_to_hi(),
1974 Applicability::MaybeIncorrect,
1980 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1981 /// it is, we try to parse the item and report error about nested types.
1982 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1983 if (self.token.is_keyword(kw::Enum)
1984 || self.token.is_keyword(kw::Struct)
1985 || self.token.is_keyword(kw::Union))
1986 && self.look_ahead(1, |t| t.is_ident())
1988 let kw_token = self.token.clone();
1989 let kw_str = pprust::token_to_string(&kw_token);
1990 let item = self.parse_item(ForceCollect::No)?;
1992 self.struct_span_err(
1994 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
1998 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2000 Applicability::MaybeIncorrect,
2003 // We successfully parsed the item but we must inform the caller about nested problem.
2010 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2012 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2014 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2015 /// were allowed to omit parameter names. In 2018, they became required.
2016 type ReqName = fn(Edition) -> bool;
2018 /// Parsing configuration for functions.
2020 /// The syntax of function items is slightly different within trait definitions,
2021 /// impl blocks, and modules. It is still parsed using the same code, just with
2022 /// different flags set, so that even when the input is wrong and produces a parse
2023 /// error, it still gets into the AST and the rest of the parser and
2024 /// type checker can run.
2025 #[derive(Clone, Copy)]
2026 pub(crate) struct FnParseMode {
2027 /// A function pointer that decides if, per-parameter `p`, `p` must have a
2028 /// pattern or just a type. This field affects parsing of the parameters list.
2031 /// fn foo(alef: A) -> X { X::new() }
2032 /// -----^^ affects parsing this part of the function signature
2034 /// if req_name returns false, then this name is optional
2039 /// if req_name returns true, this is an error
2042 /// Calling this function pointer should only return false if:
2044 /// * The item is being parsed inside of a trait definition.
2045 /// Within an impl block or a module, it should always evaluate
2047 /// * The span is from Edition 2015. In particular, you can get a
2048 /// 2015 span inside a 2021 crate using macros.
2049 pub req_name: ReqName,
2050 /// If this flag is set to `true`, then plain, semicolon-terminated function
2051 /// prototypes are not allowed here.
2054 /// fn foo(alef: A) -> X { X::new() }
2057 /// this is always allowed
2059 /// fn bar(alef: A, bet: B) -> X;
2062 /// if req_body is set to true, this is an error
2065 /// This field should only be set to false if the item is inside of a trait
2066 /// definition or extern block. Within an impl block or a module, it should
2067 /// always be set to true.
2071 /// Parsing of functions and methods.
2072 impl<'a> Parser<'a> {
2073 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2076 attrs: &mut AttrVec,
2077 fn_parse_mode: FnParseMode,
2080 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2081 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
2082 let ident = self.parse_ident()?; // `foo`
2083 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2085 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
2086 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2088 let mut sig_hi = self.prev_token.span;
2089 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2090 let fn_sig_span = sig_lo.to(sig_hi);
2091 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2094 /// Parse the "body" of a function.
2095 /// This can either be `;` when there's no body,
2096 /// or e.g. a block when the function is a provided one.
2099 attrs: &mut AttrVec,
2103 ) -> PResult<'a, Option<P<Block>>> {
2104 let has_semi = if req_body {
2105 self.token.kind == TokenKind::Semi
2107 // Only include `;` in list of expected tokens if body is not required
2108 self.check(&TokenKind::Semi)
2110 let (inner_attrs, body) = if has_semi {
2111 // Include the trailing semicolon in the span of the signature
2112 self.expect_semi()?;
2113 *sig_hi = self.prev_token.span;
2114 (AttrVec::new(), None)
2115 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2116 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2117 } else if self.token.kind == token::Eq {
2118 // Recover `fn foo() = $expr;`.
2120 let eq_sp = self.prev_token.span;
2121 let _ = self.parse_expr()?;
2122 self.expect_semi()?; // `;`
2123 let span = eq_sp.to(self.prev_token.span);
2124 self.struct_span_err(span, "function body cannot be `= expression;`")
2125 .multipart_suggestion(
2126 "surround the expression with `{` and `}` instead of `=` and `;`",
2127 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2128 Applicability::MachineApplicable,
2131 (AttrVec::new(), Some(self.mk_block_err(span)))
2133 let expected = if req_body {
2134 &[token::OpenDelim(Delimiter::Brace)][..]
2136 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2138 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2139 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2140 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2141 // the AST for typechecking.
2142 err.span_label(ident.span, "while parsing this `fn`");
2148 (AttrVec::new(), None)
2150 attrs.extend(inner_attrs);
2154 /// Is the current token the start of an `FnHeader` / not a valid parse?
2156 /// `check_pub` adds additional `pub` to the checks in case users place it
2157 /// wrongly, can be used to ensure `pub` never comes after `default`.
2158 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
2159 // We use an over-approximation here.
2160 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2161 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2162 // only if it wasn't preceded by `default` as `default pub` is invalid.
2163 let quals: &[Symbol] = if check_pub {
2164 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2166 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2168 self.check_keyword(kw::Fn) // Definitely an `fn`.
2169 // `$qual fn` or `$qual $qual`:
2170 || quals.iter().any(|&kw| self.check_keyword(kw))
2171 && self.look_ahead(1, |t| {
2172 // `$qual fn`, e.g. `const fn` or `async fn`.
2173 t.is_keyword(kw::Fn)
2174 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2175 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
2176 // Rule out 2015 `const async: T = val`.
2178 // Rule out unsafe extern block.
2179 && !self.is_unsafe_foreign_mod())
2182 || self.check_keyword(kw::Extern)
2183 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2184 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
2187 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2188 /// up to and including the `fn` keyword. The formal grammar is:
2191 /// Extern = "extern" StringLit? ;
2192 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2193 /// FnFrontMatter = FnQual "fn" ;
2196 /// `vis` represents the visibility that was already parsed, if any. Use
2197 /// `Visibility::Inherited` when no visibility is known.
2198 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2199 let sp_start = self.token.span;
2200 let constness = self.parse_constness();
2202 let async_start_sp = self.token.span;
2203 let asyncness = self.parse_asyncness();
2205 let unsafe_start_sp = self.token.span;
2206 let unsafety = self.parse_unsafety();
2208 let ext_start_sp = self.token.span;
2209 let ext = self.parse_extern();
2211 if let Async::Yes { span, .. } = asyncness {
2212 self.ban_async_in_2015(span);
2215 if !self.eat_keyword(kw::Fn) {
2216 // It is possible for `expect_one_of` to recover given the contents of
2217 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2218 // account for this.
2219 match self.expect_one_of(&[], &[]) {
2221 Ok(false) => unreachable!(),
2223 // Qualifier keywords ordering check
2229 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2230 // that the keyword is already present and the second instance should be removed.
2231 let wrong_kw = if self.check_keyword(kw::Const) {
2233 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2234 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2236 } else if self.check_keyword(kw::Async) {
2238 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2239 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2241 } else if self.check_keyword(kw::Unsafe) {
2243 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2244 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2250 // The keyword is already present, suggest removal of the second instance
2251 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2252 let original_kw = self
2253 .span_to_snippet(original_sp)
2254 .expect("Span extracted directly from keyword should always work");
2256 err.span_suggestion(
2257 self.token.uninterpolated_span(),
2258 &format!("`{original_kw}` already used earlier, remove this one"),
2260 Applicability::MachineApplicable,
2262 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2264 // The keyword has not been seen yet, suggest correct placement in the function front matter
2265 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2266 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2267 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2268 let misplaced_qual_sp = self.token.uninterpolated_span();
2269 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2271 err.span_suggestion(
2272 correct_pos_sp.to(misplaced_qual_sp),
2273 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2274 format!("{misplaced_qual} {current_qual}"),
2275 Applicability::MachineApplicable,
2276 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2279 // Recover incorrect visibility order such as `async pub`
2280 else if self.check_keyword(kw::Pub) {
2281 let sp = sp_start.to(self.prev_token.span);
2282 if let Ok(snippet) = self.span_to_snippet(sp) {
2283 let current_vis = match self.parse_visibility(FollowedByType::No) {
2290 let vs = pprust::vis_to_string(¤t_vis);
2291 let vs = vs.trim_end();
2293 // There was no explicit visibility
2294 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2295 err.span_suggestion(
2296 sp_start.to(self.prev_token.span),
2297 &format!("visibility `{vs}` must come before `{snippet}`"),
2298 format!("{vs} {snippet}"),
2299 Applicability::MachineApplicable,
2302 // There was an explicit visibility
2304 err.span_suggestion(
2306 "there is already a visibility modifier, remove one",
2308 Applicability::MachineApplicable,
2310 .span_note(orig_vis.span, "explicit visibility first seen here");
2319 Ok(FnHeader { constness, unsafety, asyncness, ext })
2322 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2323 fn ban_async_in_2015(&self, span: Span) {
2324 if span.rust_2015() {
2325 let diag = self.diagnostic();
2326 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2327 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2328 .help_use_latest_edition()
2333 /// Parses the parameter list and result type of a function declaration.
2334 pub(super) fn parse_fn_decl(
2337 ret_allow_plus: AllowPlus,
2338 recover_return_sign: RecoverReturnSign,
2339 ) -> PResult<'a, P<FnDecl>> {
2341 inputs: self.parse_fn_params(req_name)?,
2342 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2346 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2347 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2348 let mut first_param = true;
2349 // Parse the arguments, starting out with `self` being allowed...
2350 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2351 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2353 let lo = p.prev_token.span;
2354 // Skip every token until next possible arg or end.
2355 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2356 // Create a placeholder argument for proper arg count (issue #34264).
2357 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2359 // ...now that we've parsed the first argument, `self` is no longer allowed.
2360 first_param = false;
2363 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2364 self.deduplicate_recovered_params_names(&mut params);
2368 /// Parses a single function parameter.
2370 /// - `self` is syntactically allowed when `first_param` holds.
2371 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2372 let lo = self.token.span;
2373 let attrs = self.parse_outer_attributes()?;
2374 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2375 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2376 if let Some(mut param) = this.parse_self_param()? {
2377 param.attrs = attrs;
2378 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2379 return Ok((res?, TrailingToken::None));
2382 let is_name_required = match this.token.kind {
2383 token::DotDotDot => false,
2384 _ => req_name(this.token.span.edition()),
2386 let (pat, ty) = if is_name_required || this.is_named_param() {
2387 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2389 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2391 let mut err = this.unexpected::<()>().unwrap_err();
2392 return if let Some(ident) =
2393 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2396 Ok((dummy_arg(ident), TrailingToken::None))
2402 this.eat_incorrect_doc_comment_for_param_type();
2403 (pat, this.parse_ty_for_param()?)
2405 debug!("parse_param_general ident_to_pat");
2406 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2407 this.eat_incorrect_doc_comment_for_param_type();
2408 let mut ty = this.parse_ty_for_param();
2410 && this.token != token::Comma
2411 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2413 // This wasn't actually a type, but a pattern looking like a type,
2414 // so we are going to rollback and re-parse for recovery.
2415 ty = this.unexpected();
2419 let ident = Ident::new(kw::Empty, this.prev_token.span);
2420 let bm = BindingAnnotation::NONE;
2421 let pat = this.mk_pat_ident(ty.span, bm, ident);
2424 // If this is a C-variadic argument and we hit an error, return the error.
2425 Err(err) if this.token == token::DotDotDot => return Err(err),
2426 // Recover from attempting to parse the argument as a type without pattern.
2429 this.restore_snapshot(parser_snapshot_before_ty);
2430 this.recover_arg_parse()?
2435 let span = lo.to(this.prev_token.span);
2438 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2439 TrailingToken::None,
2444 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2445 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2446 // Extract an identifier *after* having confirmed that the token is one.
2447 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2448 Some((ident, false)) => {
2452 _ => unreachable!(),
2454 // Is `self` `n` tokens ahead?
2455 let is_isolated_self = |this: &Self, n| {
2456 this.is_keyword_ahead(n, &[kw::SelfLower])
2457 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2459 // Is `mut self` `n` tokens ahead?
2460 let is_isolated_mut_self =
2461 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2462 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2463 let parse_self_possibly_typed = |this: &mut Self, m| {
2464 let eself_ident = expect_self_ident(this);
2465 let eself_hi = this.prev_token.span;
2466 let eself = if this.eat(&token::Colon) {
2467 SelfKind::Explicit(this.parse_ty()?, m)
2471 Ok((eself, eself_ident, eself_hi))
2473 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2474 let recover_self_ptr = |this: &mut Self| {
2475 let msg = "cannot pass `self` by raw pointer";
2476 let span = this.token.span;
2477 this.struct_span_err(span, msg).span_label(span, msg).emit();
2479 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2482 // Parse optional `self` parameter of a method.
2483 // Only a limited set of initial token sequences is considered `self` parameters; anything
2484 // else is parsed as a normal function parameter list, so some lookahead is required.
2485 let eself_lo = self.token.span;
2486 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2487 token::BinOp(token::And) => {
2488 let eself = if is_isolated_self(self, 1) {
2491 SelfKind::Region(None, Mutability::Not)
2492 } else if is_isolated_mut_self(self, 1) {
2496 SelfKind::Region(None, Mutability::Mut)
2497 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2500 let lt = self.expect_lifetime();
2501 SelfKind::Region(Some(lt), Mutability::Not)
2502 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2505 let lt = self.expect_lifetime();
2507 SelfKind::Region(Some(lt), Mutability::Mut)
2512 (eself, expect_self_ident(self), self.prev_token.span)
2515 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2517 recover_self_ptr(self)?
2519 // `*mut self` and `*const self`
2520 token::BinOp(token::Star)
2521 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2525 recover_self_ptr(self)?
2527 // `self` and `self: TYPE`
2528 token::Ident(..) if is_isolated_self(self, 0) => {
2529 parse_self_possibly_typed(self, Mutability::Not)?
2531 // `mut self` and `mut self: TYPE`
2532 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2534 parse_self_possibly_typed(self, Mutability::Mut)?
2536 _ => return Ok(None),
2539 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2540 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2543 fn is_named_param(&self) -> bool {
2544 let offset = match self.token.kind {
2545 token::Interpolated(ref nt) => match **nt {
2546 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2549 token::BinOp(token::And) | token::AndAnd => 1,
2550 _ if self.token.is_keyword(kw::Mut) => 1,
2554 self.look_ahead(offset, |t| t.is_ident())
2555 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2558 fn recover_first_param(&mut self) -> &'static str {
2560 .parse_outer_attributes()
2561 .and_then(|_| self.parse_self_param())
2562 .map_err(|e| e.cancel())
2564 Ok(Some(_)) => "method",
2570 enum IsMacroRulesItem {
2571 Yes { has_bang: bool },