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 // Recover from using a colon as path separator.
975 while self.eat_noexpect(&token::Colon) {
976 self.struct_span_err(self.prev_token.span, "expected `::`, found `:`")
977 .span_suggestion_short(
978 self.prev_token.span,
981 Applicability::MachineApplicable,
983 .note_once("import paths are delimited using `::`")
986 // We parse the rest of the path and append it to the original prefix.
987 self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?;
988 prefix.span = lo.to(self.prev_token.span);
991 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
995 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
998 /// Parses `*` or `{...}`.
999 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
1000 Ok(if self.eat(&token::BinOp(token::Star)) {
1003 UseTreeKind::Nested(self.parse_use_tree_list()?)
1007 /// Parses a `UseTreeKind::Nested(list)`.
1010 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
1012 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1013 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
1017 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1018 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
1021 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
1022 match self.token.ident() {
1023 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
1027 _ => self.parse_ident(),
1031 /// Parses `extern crate` links.
1035 /// ```ignore (illustrative)
1036 /// extern crate foo;
1037 /// extern crate bar as foo;
1039 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1040 // Accept `extern crate name-like-this` for better diagnostics
1041 let orig_name = self.parse_crate_name_with_dashes()?;
1042 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1043 (rename, Some(orig_name.name))
1047 self.expect_semi()?;
1048 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1051 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1052 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1053 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1055 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1056 self.parse_path_segment_ident()
1060 let mut idents = vec![];
1061 let mut replacement = vec![];
1062 let mut fixed_crate_name = false;
1063 // Accept `extern crate name-like-this` for better diagnostics.
1064 let dash = token::BinOp(token::BinOpToken::Minus);
1065 if self.token == dash {
1066 // Do not include `-` as part of the expected tokens list.
1067 while self.eat(&dash) {
1068 fixed_crate_name = true;
1069 replacement.push((self.prev_token.span, "_".to_string()));
1070 idents.push(self.parse_ident()?);
1073 if fixed_crate_name {
1074 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1075 let mut fixed_name = ident.name.to_string();
1076 for part in idents {
1077 fixed_name.push_str(&format!("_{}", part.name));
1079 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1081 self.struct_span_err(fixed_name_sp, error_msg)
1082 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1083 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1089 /// Parses `extern` for foreign ABIs modules.
1091 /// `extern` is expected to have been consumed before calling this method.
1095 /// ```ignore (only-for-syntax-highlight)
1099 fn parse_item_foreign_mod(
1101 attrs: &mut AttrVec,
1102 mut unsafety: Unsafe,
1103 ) -> PResult<'a, ItemInfo> {
1104 let abi = self.parse_abi(); // ABI?
1105 if unsafety == Unsafe::No
1106 && self.token.is_keyword(kw::Unsafe)
1107 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1109 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1111 unsafety = Unsafe::Yes(self.token.span);
1112 self.eat_keyword(kw::Unsafe);
1114 let module = ast::ForeignMod {
1117 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1119 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1122 /// Parses a foreign item (one in an `extern { ... }` block).
1123 pub fn parse_foreign_item(
1125 force_collect: ForceCollect,
1126 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1127 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1128 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1129 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1130 let kind = match ForeignItemKind::try_from(kind) {
1132 Err(kind) => match kind {
1133 ItemKind::Const(_, a, b) => {
1134 self.error_on_foreign_const(span, ident);
1135 ForeignItemKind::Static(a, Mutability::Not, b)
1137 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1140 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1145 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1146 let span = self.sess.source_map().guess_head_span(span);
1147 let descr = kind.descr();
1148 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1149 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1154 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1155 self.struct_span_err(ident.span, "extern items cannot be `const`")
1157 span.with_hi(ident.span.lo()),
1158 "try using a static value",
1160 Applicability::MachineApplicable,
1162 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1166 fn is_unsafe_foreign_mod(&self) -> bool {
1167 self.token.is_keyword(kw::Unsafe)
1168 && self.is_keyword_ahead(1, &[kw::Extern])
1170 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1171 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1175 fn is_static_global(&mut self) -> bool {
1176 if self.check_keyword(kw::Static) {
1177 // Check if this could be a closure.
1178 !self.look_ahead(1, |token| {
1179 if token.is_keyword(kw::Move) {
1182 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1189 /// Recover on `const mut` with `const` already eaten.
1190 fn recover_const_mut(&mut self, const_span: Span) {
1191 if self.eat_keyword(kw::Mut) {
1192 let span = self.prev_token.span;
1193 self.struct_span_err(span, "const globals cannot be mutable")
1194 .span_label(span, "cannot be mutable")
1197 "you might want to declare a static instead",
1199 Applicability::MaybeIncorrect,
1202 } else if self.eat_keyword(kw::Let) {
1203 let span = self.prev_token.span;
1204 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1206 const_span.to(span),
1209 Applicability::MaybeIncorrect,
1215 /// Recover on `const impl` with `const` already eaten.
1216 fn recover_const_impl(
1219 attrs: &mut AttrVec,
1220 defaultness: Defaultness,
1221 ) -> PResult<'a, ItemInfo> {
1222 let impl_span = self.token.span;
1223 let mut err = self.expected_ident_found();
1225 // Only try to recover if this is implementing a trait for a type
1226 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1227 Ok(impl_info) => impl_info,
1228 Err(recovery_error) => {
1229 // Recovery failed, raise the "expected identifier" error
1230 recovery_error.cancel();
1236 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1237 *constness = Const::Yes(const_span);
1239 let before_trait = trai.path.span.shrink_to_lo();
1240 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1241 err.multipart_suggestion(
1242 "you might have meant to write a const trait impl",
1243 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1244 Applicability::MaybeIncorrect,
1248 ItemKind::Impl { .. } => return Err(err),
1249 _ => unreachable!(),
1255 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1256 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1258 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1259 fn parse_item_global(
1261 m: Option<Mutability>,
1262 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1263 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1265 // Parse the type of a `const` or `static mut?` item.
1266 // That is, the `":" $ty` fragment.
1267 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1269 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1270 (true, false) => self.parse_ty()?,
1271 (colon, _) => self.recover_missing_const_type(colon, m),
1274 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1275 self.expect_semi()?;
1279 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1280 /// This means that the type is missing.
1281 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1282 // Construct the error and stash it away with the hope
1283 // that typeck will later enrich the error with a type.
1284 let kind = match m {
1285 Some(Mutability::Mut) => "static mut",
1286 Some(Mutability::Not) => "static",
1290 let colon = match colon_present {
1295 let span = self.prev_token.span.shrink_to_hi();
1296 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1297 err.span_suggestion(
1299 "provide a type for the item",
1300 format!("{colon} <type>"),
1301 Applicability::HasPlaceholders,
1303 err.stash(span, StashKey::ItemNoType);
1305 // The user intended that the type be inferred,
1306 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1307 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1310 /// Parses an enum declaration.
1311 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1312 if self.token.is_keyword(kw::Struct) {
1313 let span = self.prev_token.span.to(self.token.span);
1314 let mut err = self.struct_span_err(span, "`enum` and `struct` are mutually exclusive");
1315 err.span_suggestion(
1317 "replace `enum struct` with",
1319 Applicability::MachineApplicable,
1321 if self.look_ahead(1, |t| t.is_ident()) {
1329 let id = self.parse_ident()?;
1330 let mut generics = self.parse_generics()?;
1331 generics.where_clause = self.parse_where_clause()?;
1333 // Possibly recover `enum Foo;` instead of `enum Foo {}`
1334 let (variants, _) = if self.token == TokenKind::Semi {
1335 self.sess.emit_err(UseEmptyBlockNotSemi { span: self.token.span });
1339 self.parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant()).map_err(
1341 e.span_label(id.span, "while parsing this enum");
1342 self.recover_stmt();
1348 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1349 Ok((id, ItemKind::Enum(enum_definition, generics)))
1352 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1353 let variant_attrs = self.parse_outer_attributes()?;
1354 self.collect_tokens_trailing_token(
1357 |this, variant_attrs| {
1358 let vlo = this.token.span;
1360 let vis = this.parse_visibility(FollowedByType::No)?;
1361 if !this.recover_nested_adt_item(kw::Enum)? {
1362 return Ok((None, TrailingToken::None));
1364 let ident = this.parse_field_ident("enum", vlo)?;
1366 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1367 // Parse a struct variant.
1368 let (fields, recovered) =
1369 this.parse_record_struct_body("struct", ident.span, false)?;
1370 VariantData::Struct(fields, recovered)
1371 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1372 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1374 VariantData::Unit(DUMMY_NODE_ID)
1378 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1380 let vr = ast::Variant {
1384 attrs: variant_attrs,
1387 span: vlo.to(this.prev_token.span),
1388 is_placeholder: false,
1391 Ok((Some(vr), TrailingToken::MaybeComma))
1396 /// Parses `struct Foo { ... }`.
1397 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1398 let class_name = self.parse_ident()?;
1400 let mut generics = self.parse_generics()?;
1402 // There is a special case worth noting here, as reported in issue #17904.
1403 // If we are parsing a tuple struct it is the case that the where clause
1404 // should follow the field list. Like so:
1406 // struct Foo<T>(T) where T: Copy;
1408 // If we are parsing a normal record-style struct it is the case
1409 // that the where clause comes before the body, and after the generics.
1410 // So if we look ahead and see a brace or a where-clause we begin
1411 // parsing a record style struct.
1413 // Otherwise if we look ahead and see a paren we parse a tuple-style
1416 let vdata = if self.token.is_keyword(kw::Where) {
1417 generics.where_clause = self.parse_where_clause()?;
1418 if self.eat(&token::Semi) {
1419 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1420 VariantData::Unit(DUMMY_NODE_ID)
1422 // If we see: `struct Foo<T> where T: Copy { ... }`
1423 let (fields, recovered) = self.parse_record_struct_body(
1426 generics.where_clause.has_where_token,
1428 VariantData::Struct(fields, recovered)
1430 // No `where` so: `struct Foo<T>;`
1431 } else if self.eat(&token::Semi) {
1432 VariantData::Unit(DUMMY_NODE_ID)
1433 // Record-style struct definition
1434 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1435 let (fields, recovered) = self.parse_record_struct_body(
1438 generics.where_clause.has_where_token,
1440 VariantData::Struct(fields, recovered)
1441 // Tuple-style struct definition with optional where-clause.
1442 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1443 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1444 generics.where_clause = self.parse_where_clause()?;
1445 self.expect_semi()?;
1448 let token_str = super::token_descr(&self.token);
1450 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1452 let mut err = self.struct_span_err(self.token.span, msg);
1453 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1457 Ok((class_name, ItemKind::Struct(vdata, generics)))
1460 /// Parses `union Foo { ... }`.
1461 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1462 let class_name = self.parse_ident()?;
1464 let mut generics = self.parse_generics()?;
1466 let vdata = if self.token.is_keyword(kw::Where) {
1467 generics.where_clause = self.parse_where_clause()?;
1468 let (fields, recovered) = self.parse_record_struct_body(
1471 generics.where_clause.has_where_token,
1473 VariantData::Struct(fields, recovered)
1474 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1475 let (fields, recovered) = self.parse_record_struct_body(
1478 generics.where_clause.has_where_token,
1480 VariantData::Struct(fields, recovered)
1482 let token_str = super::token_descr(&self.token);
1483 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1484 let mut err = self.struct_span_err(self.token.span, msg);
1485 err.span_label(self.token.span, "expected `where` or `{` after union name");
1489 Ok((class_name, ItemKind::Union(vdata, generics)))
1492 fn parse_record_struct_body(
1497 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1498 let mut fields = Vec::new();
1499 let mut recovered = false;
1500 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1501 while self.token != token::CloseDelim(Delimiter::Brace) {
1502 let field = self.parse_field_def(adt_ty).map_err(|e| {
1503 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1508 Ok(field) => fields.push(field),
1510 err.span_label(ident_span, format!("while parsing this {adt_ty}"));
1516 self.eat(&token::CloseDelim(Delimiter::Brace));
1518 let token_str = super::token_descr(&self.token);
1520 "expected {}`{{` after struct name, found {}",
1521 if parsed_where { "" } else { "`where`, or " },
1524 let mut err = self.struct_span_err(self.token.span, msg);
1528 "expected {}`{{` after struct name",
1529 if parsed_where { "" } else { "`where`, or " }
1535 Ok((fields, recovered))
1538 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1539 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1540 // Unit like structs are handled in parse_item_struct function
1541 self.parse_paren_comma_seq(|p| {
1542 let attrs = p.parse_outer_attributes()?;
1543 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1544 let lo = p.token.span;
1545 let vis = p.parse_visibility(FollowedByType::Yes)?;
1546 let ty = p.parse_ty()?;
1550 span: lo.to(ty.span),
1556 is_placeholder: false,
1558 TrailingToken::MaybeComma,
1565 /// Parses an element of a struct declaration.
1566 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1567 let attrs = self.parse_outer_attributes()?;
1568 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1569 let lo = this.token.span;
1570 let vis = this.parse_visibility(FollowedByType::No)?;
1571 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1575 /// Parses a structure field declaration.
1576 fn parse_single_struct_field(
1582 ) -> PResult<'a, FieldDef> {
1583 let mut seen_comma: bool = false;
1584 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1585 if self.token == token::Comma {
1588 if self.eat(&token::Semi) {
1589 let sp = self.prev_token.span;
1590 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1591 err.span_suggestion_short(
1593 "replace `;` with `,`",
1595 Applicability::MachineApplicable,
1599 match self.token.kind {
1603 token::CloseDelim(Delimiter::Brace) => {}
1604 token::DocComment(..) => {
1605 let previous_span = self.prev_token.span;
1606 let mut err = DocCommentDoesNotDocumentAnything {
1607 span: self.token.span,
1608 missing_comma: None,
1610 self.bump(); // consume the doc comment
1611 let comma_after_doc_seen = self.eat(&token::Comma);
1612 // `seen_comma` is always false, because we are inside doc block
1613 // condition is here to make code more readable
1614 if !seen_comma && comma_after_doc_seen {
1617 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1618 self.sess.emit_err(err);
1621 let sp = previous_span.shrink_to_hi();
1622 err.missing_comma = Some(sp);
1624 return Err(err.into_diagnostic(&self.sess.span_diagnostic));
1628 let sp = self.prev_token.span.shrink_to_hi();
1629 let mut err = self.struct_span_err(
1631 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1634 // Try to recover extra trailing angle brackets
1635 let mut recovered = false;
1636 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1637 if let Some(last_segment) = segments.last() {
1638 recovered = self.check_trailing_angle_brackets(
1640 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1643 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1645 self.eat(&token::Comma);
1646 // `check_trailing_angle_brackets` already emitted a nicer error
1647 // NOTE(eddyb) this was `.cancel()`, but `err`
1648 // gets returned, so we can't fully defuse it.
1654 if self.token.is_ident()
1655 || (self.token.kind == TokenKind::Pound
1656 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1658 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1659 // emit the diagnostic and keep going
1660 err.span_suggestion(
1662 "try adding a comma",
1664 Applicability::MachineApplicable,
1671 // Make sure an error was emitted (either by recovering an angle bracket,
1672 // or by finding an identifier as the next token), since we're
1673 // going to continue parsing
1674 assert!(self.sess.span_diagnostic.has_errors().is_some());
1683 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1684 if let Err(mut err) = self.expect(&token::Colon) {
1685 let sm = self.sess.source_map();
1686 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1687 let semi_typo = self.token.kind == token::Semi
1688 && self.look_ahead(1, |t| {
1690 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1691 // when there's no type and `;` was used instead of a comma.
1692 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1693 (Ok(l), Ok(r)) => l.line == r.line,
1697 if eq_typo || semi_typo {
1699 // Gracefully handle small typos.
1700 err.span_suggestion_short(
1701 self.prev_token.span,
1702 "field names and their types are separated with `:`",
1704 Applicability::MachineApplicable,
1714 /// Parses a structure field.
1715 fn parse_name_and_ty(
1721 ) -> PResult<'a, FieldDef> {
1722 let name = self.parse_field_ident(adt_ty, lo)?;
1723 self.expect_field_ty_separator()?;
1724 let ty = self.parse_ty()?;
1725 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1726 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1727 .span_suggestion_verbose(
1729 "write a path separator here",
1731 Applicability::MaybeIncorrect,
1735 if self.token.kind == token::Eq {
1737 let const_expr = self.parse_anon_const_expr()?;
1738 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1739 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1742 "remove this unsupported default value",
1744 Applicability::MachineApplicable,
1749 span: lo.to(self.prev_token.span),
1755 is_placeholder: false,
1759 /// Parses a field identifier. Specialized version of `parse_ident_common`
1760 /// for better diagnostics and suggestions.
1761 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1762 let (ident, is_raw) = self.ident_or_err()?;
1763 if !is_raw && ident.is_reserved() {
1764 let snapshot = self.create_snapshot_for_diagnostic();
1765 let err = if self.check_fn_front_matter(false) {
1766 let inherited_vis = Visibility {
1767 span: rustc_span::DUMMY_SP,
1768 kind: VisibilityKind::Inherited,
1771 // We use `parse_fn` to get a span for the function
1772 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1773 match self.parse_fn(&mut AttrVec::new(), fn_parse_mode, lo, &inherited_vis) {
1775 let mut err = self.struct_span_err(
1776 lo.to(self.prev_token.span),
1777 &format!("functions are not allowed in {adt_ty} definitions"),
1780 "unlike in C++, Java, and C#, functions are declared in `impl` blocks",
1782 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1787 self.restore_snapshot(snapshot);
1788 self.expected_ident_found()
1791 } else if self.eat_keyword(kw::Struct) {
1792 match self.parse_item_struct() {
1794 let mut err = self.struct_span_err(
1795 lo.with_hi(ident.span.hi()),
1796 &format!("structs are not allowed in {adt_ty} definitions"),
1798 err.help("consider creating a new `struct` definition instead of nesting");
1803 self.restore_snapshot(snapshot);
1804 self.expected_ident_found()
1808 let mut err = self.expected_ident_found();
1809 if self.eat_keyword_noexpect(kw::Let)
1810 && let removal_span = self.prev_token.span.until(self.token.span)
1811 && let Ok(ident) = self.parse_ident_common(false)
1812 // Cancel this error, we don't need it.
1813 .map_err(|err| err.cancel())
1814 && self.token.kind == TokenKind::Colon
1816 err.span_suggestion(
1818 "remove this `let` keyword",
1820 Applicability::MachineApplicable,
1822 err.note("the `let` keyword is not allowed in `struct` fields");
1823 err.note("see <https://doc.rust-lang.org/book/ch05-01-defining-structs.html> for more information");
1827 self.restore_snapshot(snapshot);
1837 /// Parses a declarative macro 2.0 definition.
1838 /// The `macro` keyword has already been parsed.
1840 /// MacBody = "{" TOKEN_STREAM "}" ;
1841 /// MacParams = "(" TOKEN_STREAM ")" ;
1842 /// DeclMac = "macro" Ident MacParams? MacBody ;
1844 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1845 let ident = self.parse_ident()?;
1846 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1847 self.parse_mac_args()? // `MacBody`
1848 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1849 let params = self.parse_token_tree(); // `MacParams`
1850 let pspan = params.span();
1851 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1852 return self.unexpected();
1854 let body = self.parse_token_tree(); // `MacBody`
1855 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1856 let bspan = body.span();
1857 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1858 let tokens = TokenStream::new(vec![params, arrow, body]);
1859 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1860 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1862 return self.unexpected();
1865 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1866 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1869 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1870 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1871 if self.check_keyword(kw::MacroRules) {
1872 let macro_rules_span = self.token.span;
1874 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1875 return IsMacroRulesItem::Yes { has_bang: true };
1876 } else if self.look_ahead(1, |t| (t.is_ident())) {
1878 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1883 Applicability::MachineApplicable,
1887 return IsMacroRulesItem::Yes { has_bang: false };
1891 IsMacroRulesItem::No
1894 /// Parses a `macro_rules! foo { ... }` declarative macro.
1895 fn parse_item_macro_rules(
1899 ) -> PResult<'a, ItemInfo> {
1900 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1903 self.expect(&token::Not)?; // `!`
1905 let ident = self.parse_ident()?;
1907 if self.eat(&token::Not) {
1908 // Handle macro_rules! foo!
1909 let span = self.prev_token.span;
1910 self.struct_span_err(span, "macro names aren't followed by a `!`")
1911 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1915 let body = self.parse_mac_args()?;
1916 self.eat_semi_for_macro_if_needed(&body);
1917 self.complain_if_pub_macro(vis, true);
1919 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1922 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1923 /// If that's not the case, emit an error.
1924 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1925 if let VisibilityKind::Inherited = vis.kind {
1929 let vstr = pprust::vis_to_string(vis);
1930 let vstr = vstr.trim_end();
1932 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1933 self.struct_span_err(vis.span, &msg)
1936 "try exporting the macro",
1938 Applicability::MaybeIncorrect, // speculative
1942 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1945 "remove the visibility",
1947 Applicability::MachineApplicable,
1949 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1954 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1955 if args.need_semicolon() && !self.eat(&token::Semi) {
1956 self.report_invalid_macro_expansion_item(args);
1960 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1961 let span = args.span().expect("undelimited macro call");
1962 let mut err = self.struct_span_err(
1964 "macros that expand to items must be delimited with braces or followed by a semicolon",
1966 // FIXME: This will make us not emit the help even for declarative
1967 // macros within the same crate (that we can fix), which is sad.
1968 if !span.from_expansion() {
1969 if self.unclosed_delims.is_empty() {
1970 let DelimSpan { open, close } = match args {
1971 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1972 MacArgs::Delimited(dspan, ..) => *dspan,
1974 err.multipart_suggestion(
1975 "change the delimiters to curly braces",
1976 vec![(open, "{".to_string()), (close, '}'.to_string())],
1977 Applicability::MaybeIncorrect,
1980 err.span_suggestion(
1982 "change the delimiters to curly braces",
1984 Applicability::HasPlaceholders,
1987 err.span_suggestion(
1988 span.shrink_to_hi(),
1991 Applicability::MaybeIncorrect,
1997 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1998 /// it is, we try to parse the item and report error about nested types.
1999 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
2000 if (self.token.is_keyword(kw::Enum)
2001 || self.token.is_keyword(kw::Struct)
2002 || self.token.is_keyword(kw::Union))
2003 && self.look_ahead(1, |t| t.is_ident())
2005 let kw_token = self.token.clone();
2006 let kw_str = pprust::token_to_string(&kw_token);
2007 let item = self.parse_item(ForceCollect::No)?;
2009 self.struct_span_err(
2011 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
2015 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
2017 Applicability::MaybeIncorrect,
2020 // We successfully parsed the item but we must inform the caller about nested problem.
2027 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
2029 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
2031 /// This function pointer accepts an edition, because in edition 2015, trait declarations
2032 /// were allowed to omit parameter names. In 2018, they became required.
2033 type ReqName = fn(Edition) -> bool;
2035 /// Parsing configuration for functions.
2037 /// The syntax of function items is slightly different within trait definitions,
2038 /// impl blocks, and modules. It is still parsed using the same code, just with
2039 /// different flags set, so that even when the input is wrong and produces a parse
2040 /// error, it still gets into the AST and the rest of the parser and
2041 /// type checker can run.
2042 #[derive(Clone, Copy)]
2043 pub(crate) struct FnParseMode {
2044 /// A function pointer that decides if, per-parameter `p`, `p` must have a
2045 /// pattern or just a type. This field affects parsing of the parameters list.
2048 /// fn foo(alef: A) -> X { X::new() }
2049 /// -----^^ affects parsing this part of the function signature
2051 /// if req_name returns false, then this name is optional
2056 /// if req_name returns true, this is an error
2059 /// Calling this function pointer should only return false if:
2061 /// * The item is being parsed inside of a trait definition.
2062 /// Within an impl block or a module, it should always evaluate
2064 /// * The span is from Edition 2015. In particular, you can get a
2065 /// 2015 span inside a 2021 crate using macros.
2066 pub req_name: ReqName,
2067 /// If this flag is set to `true`, then plain, semicolon-terminated function
2068 /// prototypes are not allowed here.
2071 /// fn foo(alef: A) -> X { X::new() }
2074 /// this is always allowed
2076 /// fn bar(alef: A, bet: B) -> X;
2079 /// if req_body is set to true, this is an error
2082 /// This field should only be set to false if the item is inside of a trait
2083 /// definition or extern block. Within an impl block or a module, it should
2084 /// always be set to true.
2088 /// Parsing of functions and methods.
2089 impl<'a> Parser<'a> {
2090 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2093 attrs: &mut AttrVec,
2094 fn_parse_mode: FnParseMode,
2097 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2098 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
2099 let ident = self.parse_ident()?; // `foo`
2100 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2102 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
2103 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2105 let mut sig_hi = self.prev_token.span;
2106 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2107 let fn_sig_span = sig_lo.to(sig_hi);
2108 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2111 /// Parse the "body" of a function.
2112 /// This can either be `;` when there's no body,
2113 /// or e.g. a block when the function is a provided one.
2116 attrs: &mut AttrVec,
2120 ) -> PResult<'a, Option<P<Block>>> {
2121 let has_semi = if req_body {
2122 self.token.kind == TokenKind::Semi
2124 // Only include `;` in list of expected tokens if body is not required
2125 self.check(&TokenKind::Semi)
2127 let (inner_attrs, body) = if has_semi {
2128 // Include the trailing semicolon in the span of the signature
2129 self.expect_semi()?;
2130 *sig_hi = self.prev_token.span;
2131 (AttrVec::new(), None)
2132 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2133 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2134 } else if self.token.kind == token::Eq {
2135 // Recover `fn foo() = $expr;`.
2137 let eq_sp = self.prev_token.span;
2138 let _ = self.parse_expr()?;
2139 self.expect_semi()?; // `;`
2140 let span = eq_sp.to(self.prev_token.span);
2141 self.struct_span_err(span, "function body cannot be `= expression;`")
2142 .multipart_suggestion(
2143 "surround the expression with `{` and `}` instead of `=` and `;`",
2144 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2145 Applicability::MachineApplicable,
2148 (AttrVec::new(), Some(self.mk_block_err(span)))
2150 let expected = if req_body {
2151 &[token::OpenDelim(Delimiter::Brace)][..]
2153 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2155 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2156 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2157 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2158 // the AST for typechecking.
2159 err.span_label(ident.span, "while parsing this `fn`");
2165 (AttrVec::new(), None)
2167 attrs.extend(inner_attrs);
2171 /// Is the current token the start of an `FnHeader` / not a valid parse?
2173 /// `check_pub` adds additional `pub` to the checks in case users place it
2174 /// wrongly, can be used to ensure `pub` never comes after `default`.
2175 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
2176 // We use an over-approximation here.
2177 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2178 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2179 // only if it wasn't preceded by `default` as `default pub` is invalid.
2180 let quals: &[Symbol] = if check_pub {
2181 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2183 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2185 self.check_keyword(kw::Fn) // Definitely an `fn`.
2186 // `$qual fn` or `$qual $qual`:
2187 || quals.iter().any(|&kw| self.check_keyword(kw))
2188 && self.look_ahead(1, |t| {
2189 // `$qual fn`, e.g. `const fn` or `async fn`.
2190 t.is_keyword(kw::Fn)
2191 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2192 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
2193 // Rule out 2015 `const async: T = val`.
2195 // Rule out unsafe extern block.
2196 && !self.is_unsafe_foreign_mod())
2199 || self.check_keyword(kw::Extern)
2200 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2201 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
2204 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2205 /// up to and including the `fn` keyword. The formal grammar is:
2208 /// Extern = "extern" StringLit? ;
2209 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2210 /// FnFrontMatter = FnQual "fn" ;
2213 /// `vis` represents the visibility that was already parsed, if any. Use
2214 /// `Visibility::Inherited` when no visibility is known.
2215 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2216 let sp_start = self.token.span;
2217 let constness = self.parse_constness();
2219 let async_start_sp = self.token.span;
2220 let asyncness = self.parse_asyncness();
2222 let unsafe_start_sp = self.token.span;
2223 let unsafety = self.parse_unsafety();
2225 let ext_start_sp = self.token.span;
2226 let ext = self.parse_extern();
2228 if let Async::Yes { span, .. } = asyncness {
2229 self.ban_async_in_2015(span);
2232 if !self.eat_keyword(kw::Fn) {
2233 // It is possible for `expect_one_of` to recover given the contents of
2234 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2235 // account for this.
2236 match self.expect_one_of(&[], &[]) {
2238 Ok(false) => unreachable!(),
2240 // Qualifier keywords ordering check
2246 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2247 // that the keyword is already present and the second instance should be removed.
2248 let wrong_kw = if self.check_keyword(kw::Const) {
2250 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2251 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2253 } else if self.check_keyword(kw::Async) {
2255 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2256 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2258 } else if self.check_keyword(kw::Unsafe) {
2260 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2261 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2267 // The keyword is already present, suggest removal of the second instance
2268 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2269 let original_kw = self
2270 .span_to_snippet(original_sp)
2271 .expect("Span extracted directly from keyword should always work");
2273 err.span_suggestion(
2274 self.token.uninterpolated_span(),
2275 &format!("`{original_kw}` already used earlier, remove this one"),
2277 Applicability::MachineApplicable,
2279 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2281 // The keyword has not been seen yet, suggest correct placement in the function front matter
2282 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2283 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2284 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2285 let misplaced_qual_sp = self.token.uninterpolated_span();
2286 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2288 err.span_suggestion(
2289 correct_pos_sp.to(misplaced_qual_sp),
2290 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2291 format!("{misplaced_qual} {current_qual}"),
2292 Applicability::MachineApplicable,
2293 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2296 // Recover incorrect visibility order such as `async pub`
2297 else if self.check_keyword(kw::Pub) {
2298 let sp = sp_start.to(self.prev_token.span);
2299 if let Ok(snippet) = self.span_to_snippet(sp) {
2300 let current_vis = match self.parse_visibility(FollowedByType::No) {
2307 let vs = pprust::vis_to_string(¤t_vis);
2308 let vs = vs.trim_end();
2310 // There was no explicit visibility
2311 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2312 err.span_suggestion(
2313 sp_start.to(self.prev_token.span),
2314 &format!("visibility `{vs}` must come before `{snippet}`"),
2315 format!("{vs} {snippet}"),
2316 Applicability::MachineApplicable,
2319 // There was an explicit visibility
2321 err.span_suggestion(
2323 "there is already a visibility modifier, remove one",
2325 Applicability::MachineApplicable,
2327 .span_note(orig_vis.span, "explicit visibility first seen here");
2336 Ok(FnHeader { constness, unsafety, asyncness, ext })
2339 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2340 fn ban_async_in_2015(&self, span: Span) {
2341 if span.rust_2015() {
2342 let diag = self.diagnostic();
2343 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2344 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2345 .help_use_latest_edition()
2350 /// Parses the parameter list and result type of a function declaration.
2351 pub(super) fn parse_fn_decl(
2354 ret_allow_plus: AllowPlus,
2355 recover_return_sign: RecoverReturnSign,
2356 ) -> PResult<'a, P<FnDecl>> {
2358 inputs: self.parse_fn_params(req_name)?,
2359 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2363 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2364 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2365 let mut first_param = true;
2366 // Parse the arguments, starting out with `self` being allowed...
2367 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2368 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2370 let lo = p.prev_token.span;
2371 // Skip every token until next possible arg or end.
2372 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2373 // Create a placeholder argument for proper arg count (issue #34264).
2374 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2376 // ...now that we've parsed the first argument, `self` is no longer allowed.
2377 first_param = false;
2380 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2381 self.deduplicate_recovered_params_names(&mut params);
2385 /// Parses a single function parameter.
2387 /// - `self` is syntactically allowed when `first_param` holds.
2388 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2389 let lo = self.token.span;
2390 let attrs = self.parse_outer_attributes()?;
2391 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2392 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2393 if let Some(mut param) = this.parse_self_param()? {
2394 param.attrs = attrs;
2395 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2396 return Ok((res?, TrailingToken::None));
2399 let is_name_required = match this.token.kind {
2400 token::DotDotDot => false,
2401 _ => req_name(this.token.span.edition()),
2403 let (pat, ty) = if is_name_required || this.is_named_param() {
2404 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2406 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2408 let mut err = this.unexpected::<()>().unwrap_err();
2409 return if let Some(ident) =
2410 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2413 Ok((dummy_arg(ident), TrailingToken::None))
2419 this.eat_incorrect_doc_comment_for_param_type();
2420 (pat, this.parse_ty_for_param()?)
2422 debug!("parse_param_general ident_to_pat");
2423 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2424 this.eat_incorrect_doc_comment_for_param_type();
2425 let mut ty = this.parse_ty_for_param();
2427 && this.token != token::Comma
2428 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2430 // This wasn't actually a type, but a pattern looking like a type,
2431 // so we are going to rollback and re-parse for recovery.
2432 ty = this.unexpected();
2436 let ident = Ident::new(kw::Empty, this.prev_token.span);
2437 let bm = BindingAnnotation::NONE;
2438 let pat = this.mk_pat_ident(ty.span, bm, ident);
2441 // If this is a C-variadic argument and we hit an error, return the error.
2442 Err(err) if this.token == token::DotDotDot => return Err(err),
2443 // Recover from attempting to parse the argument as a type without pattern.
2446 this.restore_snapshot(parser_snapshot_before_ty);
2447 this.recover_arg_parse()?
2452 let span = lo.to(this.prev_token.span);
2455 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2456 TrailingToken::None,
2461 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2462 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2463 // Extract an identifier *after* having confirmed that the token is one.
2464 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2465 Some((ident, false)) => {
2469 _ => unreachable!(),
2471 // Is `self` `n` tokens ahead?
2472 let is_isolated_self = |this: &Self, n| {
2473 this.is_keyword_ahead(n, &[kw::SelfLower])
2474 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2476 // Is `mut self` `n` tokens ahead?
2477 let is_isolated_mut_self =
2478 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2479 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2480 let parse_self_possibly_typed = |this: &mut Self, m| {
2481 let eself_ident = expect_self_ident(this);
2482 let eself_hi = this.prev_token.span;
2483 let eself = if this.eat(&token::Colon) {
2484 SelfKind::Explicit(this.parse_ty()?, m)
2488 Ok((eself, eself_ident, eself_hi))
2490 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2491 let recover_self_ptr = |this: &mut Self| {
2492 let msg = "cannot pass `self` by raw pointer";
2493 let span = this.token.span;
2494 this.struct_span_err(span, msg).span_label(span, msg).emit();
2496 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2499 // Parse optional `self` parameter of a method.
2500 // Only a limited set of initial token sequences is considered `self` parameters; anything
2501 // else is parsed as a normal function parameter list, so some lookahead is required.
2502 let eself_lo = self.token.span;
2503 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2504 token::BinOp(token::And) => {
2505 let eself = if is_isolated_self(self, 1) {
2508 SelfKind::Region(None, Mutability::Not)
2509 } else if is_isolated_mut_self(self, 1) {
2513 SelfKind::Region(None, Mutability::Mut)
2514 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2517 let lt = self.expect_lifetime();
2518 SelfKind::Region(Some(lt), Mutability::Not)
2519 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2522 let lt = self.expect_lifetime();
2524 SelfKind::Region(Some(lt), Mutability::Mut)
2529 (eself, expect_self_ident(self), self.prev_token.span)
2532 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2534 recover_self_ptr(self)?
2536 // `*mut self` and `*const self`
2537 token::BinOp(token::Star)
2538 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2542 recover_self_ptr(self)?
2544 // `self` and `self: TYPE`
2545 token::Ident(..) if is_isolated_self(self, 0) => {
2546 parse_self_possibly_typed(self, Mutability::Not)?
2548 // `mut self` and `mut self: TYPE`
2549 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2551 parse_self_possibly_typed(self, Mutability::Mut)?
2553 _ => return Ok(None),
2556 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2557 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2560 fn is_named_param(&self) -> bool {
2561 let offset = match self.token.kind {
2562 token::Interpolated(ref nt) => match **nt {
2563 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2566 token::BinOp(token::And) | token::AndAnd => 1,
2567 _ if self.token.is_keyword(kw::Mut) => 1,
2571 self.look_ahead(offset, |t| t.is_ident())
2572 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2575 fn recover_first_param(&mut self) -> &'static str {
2577 .parse_outer_attributes()
2578 .and_then(|_| self.parse_self_param())
2579 .map_err(|e| e.cancel())
2581 Ok(Some(_)) => "method",
2587 enum IsMacroRulesItem {
2588 Yes { has_bang: bool },