1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
3 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
7 use rustc_ast::token::{self, Delimiter, TokenKind};
8 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
9 use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
10 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
11 use rustc_ast::{BindingMode, Block, FnDecl, FnSig, Param, SelfKind};
12 use rustc_ast::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData};
13 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
14 use rustc_ast::{MacArgs, MacCall, MacDelimiter};
15 use rustc_ast_pretty::pprust;
16 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
17 use rustc_span::edition::Edition;
18 use rustc_span::lev_distance::lev_distance;
19 use rustc_span::source_map::{self, Span};
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::DUMMY_SP;
23 use std::convert::TryFrom;
28 /// Parses a source module as a crate. This is the main entry point for the parser.
29 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
30 let (attrs, items, spans) = self.parse_mod(&token::Eof)?;
31 Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
34 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
35 fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
36 let unsafety = self.parse_unsafety();
37 self.expect_keyword(kw::Mod)?;
38 let id = self.parse_ident()?;
39 let mod_kind = if self.eat(&token::Semi) {
42 self.expect(&token::OpenDelim(Delimiter::Brace))?;
43 let (mut inner_attrs, items, inner_span) =
44 self.parse_mod(&token::CloseDelim(Delimiter::Brace))?;
45 attrs.append(&mut inner_attrs);
46 ModKind::Loaded(items, Inline::Yes, inner_span)
48 Ok((id, ItemKind::Mod(unsafety, mod_kind)))
51 /// Parses the contents of a module (inner attributes followed by module items).
55 ) -> PResult<'a, (Vec<Attribute>, Vec<P<Item>>, ModSpans)> {
56 let lo = self.token.span;
57 let attrs = self.parse_inner_attributes()?;
59 let post_attr_lo = self.token.span;
60 let mut items = vec![];
61 while let Some(item) = self.parse_item(ForceCollect::No)? {
63 self.maybe_consume_incorrect_semicolon(&items);
67 let token_str = super::token_descr(&self.token);
68 if !self.maybe_consume_incorrect_semicolon(&items) {
69 let msg = &format!("expected item, found {token_str}");
70 let mut err = self.struct_span_err(self.token.span, msg);
71 err.span_label(self.token.span, "expected item");
76 let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
77 let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
78 Ok((attrs, items, mod_spans))
82 pub(super) type ItemInfo = (Ident, ItemKind);
85 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
86 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
87 self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
92 fn_parse_mode: FnParseMode,
93 force_collect: ForceCollect,
94 ) -> PResult<'a, Option<Item>> {
95 let attrs = self.parse_outer_attributes()?;
96 self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
99 pub(super) fn parse_item_common(
104 fn_parse_mode: FnParseMode,
105 force_collect: ForceCollect,
106 ) -> PResult<'a, Option<Item>> {
107 // Don't use `maybe_whole` so that we have precise control
108 // over when we bump the parser
109 if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
110 let mut item = item.clone();
113 attrs.prepend_to_nt_inner(&mut item.attrs);
114 return Ok(Some(item.into_inner()));
117 let mut unclosed_delims = vec![];
119 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
121 this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
122 unclosed_delims.append(&mut this.unclosed_delims);
123 Ok((item?, TrailingToken::None))
126 self.unclosed_delims.append(&mut unclosed_delims);
130 fn parse_item_common_(
132 mut attrs: Vec<Attribute>,
135 fn_parse_mode: FnParseMode,
136 ) -> PResult<'a, Option<Item>> {
137 let lo = self.token.span;
138 let vis = self.parse_visibility(FollowedByType::No)?;
139 let mut def = self.parse_defaultness();
141 self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, fn_parse_mode)?;
142 if let Some((ident, kind)) = kind {
143 self.error_on_unconsumed_default(def, &kind);
144 let span = lo.to(self.prev_token.span);
145 let id = DUMMY_NODE_ID;
146 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
147 return Ok(Some(item));
150 // At this point, we have failed to parse an item.
151 self.error_on_unmatched_vis(&vis);
152 self.error_on_unmatched_defaultness(def);
154 self.recover_attrs_no_item(&attrs)?;
159 /// Error in-case a non-inherited visibility was parsed but no item followed.
160 fn error_on_unmatched_vis(&self, vis: &Visibility) {
161 if let VisibilityKind::Inherited = vis.kind {
164 let vs = pprust::vis_to_string(&vis);
165 let vs = vs.trim_end();
166 self.struct_span_err(vis.span, &format!("visibility `{vs}` is not followed by an item"))
167 .span_label(vis.span, "the visibility")
168 .help(&format!("you likely meant to define an item, e.g., `{vs} fn foo() {{}}`"))
172 /// Error in-case a `default` was parsed but no item followed.
173 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
174 if let Defaultness::Default(sp) = def {
175 self.struct_span_err(sp, "`default` is not followed by an item")
176 .span_label(sp, "the `default` qualifier")
177 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
182 /// Error in-case `default` was parsed in an in-appropriate context.
183 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
184 if let Defaultness::Default(span) = def {
185 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
186 self.struct_span_err(span, &msg)
187 .span_label(span, "`default` because of this")
188 .note("only associated `fn`, `const`, and `type` items can be `default`")
193 /// Parses one of the items allowed by the flags.
196 attrs: &mut Vec<Attribute>,
197 macros_allowed: bool,
200 def: &mut Defaultness,
201 fn_parse_mode: FnParseMode,
202 ) -> PResult<'a, Option<ItemInfo>> {
203 let def_final = def == &Defaultness::Final;
204 let mut def = || mem::replace(def, Defaultness::Final);
206 let info = if self.eat_keyword(kw::Use) {
207 self.parse_use_item()?
208 } else if self.check_fn_front_matter(def_final) {
210 let (ident, sig, generics, body) = self.parse_fn(attrs, fn_parse_mode, lo, vis)?;
211 (ident, ItemKind::Fn(Box::new(Fn { defaultness: def(), sig, generics, body })))
212 } else if self.eat_keyword(kw::Extern) {
213 if self.eat_keyword(kw::Crate) {
215 self.parse_item_extern_crate()?
218 self.parse_item_foreign_mod(attrs, Unsafe::No)?
220 } else if self.is_unsafe_foreign_mod() {
222 let unsafety = self.parse_unsafety();
223 self.expect_keyword(kw::Extern)?;
224 self.parse_item_foreign_mod(attrs, unsafety)?
225 } else if self.is_static_global() {
227 self.bump(); // `static`
228 let m = self.parse_mutability();
229 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
230 (ident, ItemKind::Static(ty, m, expr))
231 } else if let Const::Yes(const_span) = self.parse_constness() {
233 if self.token.is_keyword(kw::Impl) {
234 // recover from `const impl`, suggest `impl const`
235 self.recover_const_impl(const_span, attrs, def())?
237 self.recover_const_mut(const_span);
238 let (ident, ty, expr) = self.parse_item_global(None)?;
239 (ident, ItemKind::Const(def(), ty, expr))
241 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
243 self.parse_item_trait(attrs, lo)?
244 } else if self.check_keyword(kw::Impl)
245 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
248 self.parse_item_impl(attrs, def())?
249 } else if self.check_keyword(kw::Mod)
250 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
253 self.parse_item_mod(attrs)?
254 } else if self.eat_keyword(kw::Type) {
256 self.parse_type_alias(def())?
257 } else if self.eat_keyword(kw::Enum) {
259 self.parse_item_enum()?
260 } else if self.eat_keyword(kw::Struct) {
262 self.parse_item_struct()?
263 } else if self.is_kw_followed_by_ident(kw::Union) {
265 self.bump(); // `union`
266 self.parse_item_union()?
267 } else if self.eat_keyword(kw::Macro) {
269 self.parse_item_decl_macro(lo)?
270 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
272 self.parse_item_macro_rules(vis, has_bang)?
273 } else if self.isnt_macro_invocation()
274 && (self.token.is_ident_named(sym::import) || self.token.is_ident_named(sym::using))
276 return self.recover_import_as_use();
277 } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
278 self.recover_missing_kw_before_item()?;
280 } else if macros_allowed && self.check_path() {
281 // MACRO INVOCATION ITEM
282 (Ident::empty(), ItemKind::MacCall(self.parse_item_macro(vis)?))
289 fn recover_import_as_use(&mut self) -> PResult<'a, Option<(Ident, ItemKind)>> {
290 let span = self.token.span;
291 let token_name = super::token_descr(&self.token);
292 let snapshot = self.create_snapshot_for_diagnostic();
294 match self.parse_use_item() {
296 self.struct_span_err(span, format!("expected item, found {token_name}"))
297 .span_suggestion_short(
299 "items are imported using the `use` keyword",
301 Applicability::MachineApplicable,
308 self.restore_snapshot(snapshot);
314 fn parse_use_item(&mut self) -> PResult<'a, (Ident, ItemKind)> {
315 let tree = self.parse_use_tree()?;
316 if let Err(mut e) = self.expect_semi() {
318 UseTreeKind::Glob => {
319 e.note("the wildcard token must be last on the path");
321 UseTreeKind::Nested(..) => {
322 e.note("glob-like brace syntax must be last on the path");
328 Ok((Ident::empty(), ItemKind::Use(tree)))
331 /// When parsing a statement, would the start of a path be an item?
332 pub(super) fn is_path_start_item(&mut self) -> bool {
333 self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
334 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
335 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
336 || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
339 /// Are we sure this could not possibly be a macro invocation?
340 fn isnt_macro_invocation(&mut self) -> bool {
341 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
344 /// Recover on encountering a struct or method definition where the user
345 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
346 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
347 // Space between `pub` keyword and the identifier
350 // ^^^ `sp` points here
351 let sp = self.prev_token.span.between(self.token.span);
352 let full_sp = self.prev_token.span.to(self.token.span);
353 let ident_sp = self.token.span;
354 if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace)) {
355 // possible public struct definition where `struct` was forgotten
356 let ident = self.parse_ident().unwrap();
357 let msg = format!("add `struct` here to parse `{ident}` as a public struct");
358 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
359 err.span_suggestion_short(
363 Applicability::MaybeIncorrect, // speculative
366 } else if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Parenthesis)) {
367 let ident = self.parse_ident().unwrap();
369 let kw_name = self.recover_first_param();
370 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::Yes);
371 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
372 self.eat_to_tokens(&[&token::OpenDelim(Delimiter::Brace)]);
374 ("fn", kw_name, false)
375 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
377 ("fn", kw_name, false)
378 } else if self.check(&token::Colon) {
382 ("fn` or `struct", "function or struct", true)
385 let msg = format!("missing `{kw}` for {kw_name} definition");
386 let mut err = self.struct_span_err(sp, &msg);
388 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
390 format!("add `{kw}` here to parse `{ident}` as a public {kw_name}");
391 err.span_suggestion_short(
395 Applicability::MachineApplicable,
397 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
400 "if you meant to call a macro, try",
401 format!("{}!", snippet),
402 // this is the `ambiguous` conditional branch
403 Applicability::MaybeIncorrect,
407 "if you meant to call a macro, remove the `pub` \
408 and add a trailing `!` after the identifier",
412 } else if self.look_ahead(1, |t| *t == token::Lt) {
413 let ident = self.parse_ident().unwrap();
414 self.eat_to_tokens(&[&token::Gt]);
416 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(Delimiter::Parenthesis)) {
417 ("fn", self.recover_first_param(), false)
418 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
419 ("struct", "struct", false)
421 ("fn` or `struct", "function or struct", true)
423 let msg = format!("missing `{kw}` for {kw_name} definition");
424 let mut err = self.struct_span_err(sp, &msg);
426 err.span_suggestion_short(
428 &format!("add `{kw}` here to parse `{ident}` as a public {kw_name}"),
430 Applicability::MachineApplicable,
439 /// Parses an item macro, e.g., `item!();`.
440 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
441 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
442 self.expect(&token::Not)?; // `!`
443 match self.parse_mac_args() {
444 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
446 self.eat_semi_for_macro_if_needed(&args);
447 self.complain_if_pub_macro(vis, false);
448 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
452 // Maybe the user misspelled `macro_rules` (issue #91227)
453 if self.token.is_ident()
454 && path.segments.len() == 1
455 && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
459 "perhaps you meant to define a macro",
461 Applicability::MachineApplicable,
469 /// Recover if we parsed attributes and expected an item but there was none.
470 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
471 let ([start @ end] | [start, .., end]) = attrs else {
474 let msg = if end.is_doc_comment() {
475 "expected item after doc comment"
477 "expected item after attributes"
479 let mut err = self.struct_span_err(end.span, msg);
480 if end.is_doc_comment() {
481 err.span_label(end.span, "this doc comment doesn't document anything");
483 if end.meta_kind().is_some() {
484 if self.token.kind == TokenKind::Semi {
485 err.span_suggestion_verbose(
487 "consider removing this semicolon",
489 Applicability::MaybeIncorrect,
493 if let [.., penultimate, _] = attrs {
494 err.span_label(start.span.to(penultimate.span), "other attributes here");
499 fn is_async_fn(&self) -> bool {
500 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
503 fn parse_polarity(&mut self) -> ast::ImplPolarity {
504 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
505 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
507 ast::ImplPolarity::Negative(self.prev_token.span)
509 ast::ImplPolarity::Positive
513 /// Parses an implementation item.
515 /// ```ignore (illustrative)
516 /// impl<'a, T> TYPE { /* impl items */ }
517 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
518 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
519 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
522 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
524 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
525 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
529 attrs: &mut Vec<Attribute>,
530 defaultness: Defaultness,
531 ) -> PResult<'a, ItemInfo> {
532 let unsafety = self.parse_unsafety();
533 self.expect_keyword(kw::Impl)?;
535 // First, parse generic parameters if necessary.
536 let mut generics = if self.choose_generics_over_qpath(0) {
537 self.parse_generics()?
539 let mut generics = Generics::default();
541 // /\ this is where `generics.span` should point when there are no type params.
542 generics.span = self.prev_token.span.shrink_to_hi();
546 let constness = self.parse_constness();
547 if let Const::Yes(span) = constness {
548 self.sess.gated_spans.gate(sym::const_trait_impl, span);
551 let polarity = self.parse_polarity();
553 // Parse both types and traits as a type, then reinterpret if necessary.
554 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
555 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
557 let span = self.prev_token.span.between(self.token.span);
558 self.struct_span_err(span, "missing trait in a trait impl")
563 Applicability::HasPlaceholders,
566 span.to(self.token.span),
567 "for an inherent impl, drop this `for`",
569 Applicability::MaybeIncorrect,
573 kind: TyKind::Path(None, err_path(span)),
579 self.parse_ty_with_generics_recovery(&generics)?
582 // If `for` is missing we try to recover.
583 let has_for = self.eat_keyword(kw::For);
584 let missing_for_span = self.prev_token.span.between(self.token.span);
586 let ty_second = if self.token == token::DotDot {
587 // We need to report this error after `cfg` expansion for compatibility reasons
588 self.bump(); // `..`, do not add it to expected tokens
589 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
590 } else if has_for || self.token.can_begin_type() {
591 Some(self.parse_ty()?)
596 generics.where_clause = self.parse_where_clause()?;
598 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
600 let item_kind = match ty_second {
602 // impl Trait for Type
604 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
605 .span_suggestion_short(
609 Applicability::MachineApplicable,
614 let ty_first = ty_first.into_inner();
615 let path = match ty_first.kind {
616 // This notably includes paths passed through `ty` macro fragments (#46438).
617 TyKind::Path(None, path) => path,
619 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
620 err_path(ty_first.span)
623 let trait_ref = TraitRef { path, ref_id: ty_first.id };
625 ItemKind::Impl(Box::new(Impl {
631 of_trait: Some(trait_ref),
638 ItemKind::Impl(Box::new(Impl {
651 Ok((Ident::empty(), item_kind))
654 fn parse_item_list<T>(
656 attrs: &mut Vec<Attribute>,
657 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
658 ) -> PResult<'a, Vec<T>> {
659 let open_brace_span = self.token.span;
660 self.expect(&token::OpenDelim(Delimiter::Brace))?;
661 attrs.append(&mut self.parse_inner_attributes()?);
663 let mut items = Vec::new();
664 while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
665 if self.recover_doc_comment_before_brace() {
668 match parse_item(self) {
670 // We have to bail or we'll potentially never make progress.
671 let non_item_span = self.token.span;
672 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
673 self.struct_span_err(non_item_span, "non-item in item list")
674 .span_label(open_brace_span, "item list starts here")
675 .span_label(non_item_span, "non-item starts here")
676 .span_label(self.prev_token.span, "item list ends here")
680 Ok(Some(item)) => items.extend(item),
682 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
683 err.span_label(open_brace_span, "while parsing this item list starting here")
684 .span_label(self.prev_token.span, "the item list ends here")
693 /// Recover on a doc comment before `}`.
694 fn recover_doc_comment_before_brace(&mut self) -> bool {
695 if let token::DocComment(..) = self.token.kind {
696 if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
701 "found a documentation comment that doesn't document anything",
703 .span_label(self.token.span, "this doc comment doesn't document anything")
705 "doc comments must come before what they document, maybe a \
706 comment was intended with `//`?",
716 /// Parses defaultness (i.e., `default` or nothing).
717 fn parse_defaultness(&mut self) -> Defaultness {
718 // We are interested in `default` followed by another identifier.
719 // However, we must avoid keywords that occur as binary operators.
720 // Currently, the only applicable keyword is `as` (`default as Ty`).
721 if self.check_keyword(kw::Default)
722 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
724 self.bump(); // `default`
725 Defaultness::Default(self.prev_token.uninterpolated_span())
731 /// Is this an `(unsafe auto? | auto) trait` item?
732 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
734 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
736 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
739 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
740 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
741 let unsafety = self.parse_unsafety();
742 // Parse optional `auto` prefix.
743 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
745 self.expect_keyword(kw::Trait)?;
746 let ident = self.parse_ident()?;
747 let mut generics = self.parse_generics()?;
749 // Parse optional colon and supertrait bounds.
750 let had_colon = self.eat(&token::Colon);
751 let span_at_colon = self.prev_token.span;
752 let bounds = if had_colon {
753 self.parse_generic_bounds(Some(self.prev_token.span))?
758 let span_before_eq = self.prev_token.span;
759 if self.eat(&token::Eq) {
760 // It's a trait alias.
762 let span = span_at_colon.to(span_before_eq);
763 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
766 let bounds = self.parse_generic_bounds(None)?;
767 generics.where_clause = self.parse_where_clause()?;
770 let whole_span = lo.to(self.prev_token.span);
771 if is_auto == IsAuto::Yes {
772 let msg = "trait aliases cannot be `auto`";
773 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
775 if let Unsafe::Yes(_) = unsafety {
776 let msg = "trait aliases cannot be `unsafe`";
777 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
780 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
782 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
784 // It's a normal trait.
785 generics.where_clause = self.parse_where_clause()?;
786 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
789 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
794 pub fn parse_impl_item(
796 force_collect: ForceCollect,
797 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
798 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
799 self.parse_assoc_item(fn_parse_mode, force_collect)
802 pub fn parse_trait_item(
804 force_collect: ForceCollect,
805 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
807 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
808 self.parse_assoc_item(fn_parse_mode, force_collect)
811 /// Parses associated items.
814 fn_parse_mode: FnParseMode,
815 force_collect: ForceCollect,
816 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
817 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
818 |Item { attrs, id, span, vis, ident, kind, tokens }| {
819 let kind = match AssocItemKind::try_from(kind) {
821 Err(kind) => match kind {
822 ItemKind::Static(a, _, b) => {
823 self.struct_span_err(span, "associated `static` items are not allowed")
825 AssocItemKind::Const(Defaultness::Final, a, b)
827 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
830 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
835 /// Parses a `type` alias with the following grammar:
837 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
839 /// The `"type"` has already been eaten.
840 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
841 let ident = self.parse_ident()?;
842 let mut generics = self.parse_generics()?;
844 // Parse optional colon and param bounds.
846 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
847 let before_where_clause = self.parse_where_clause()?;
849 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
851 let after_where_clause = self.parse_where_clause()?;
853 let where_clauses = (
854 TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
855 TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
857 let where_predicates_split = before_where_clause.predicates.len();
858 let mut predicates = before_where_clause.predicates;
859 predicates.extend(after_where_clause.predicates.into_iter());
860 let where_clause = WhereClause {
861 has_where_token: before_where_clause.has_where_token
862 || after_where_clause.has_where_token,
866 generics.where_clause = where_clause;
872 ItemKind::TyAlias(Box::new(TyAlias {
876 where_predicates_split,
883 /// Parses a `UseTree`.
886 /// USE_TREE = [`::`] `*` |
887 /// [`::`] `{` USE_TREE_LIST `}` |
889 /// PATH `::` `{` USE_TREE_LIST `}` |
890 /// PATH [`as` IDENT]
892 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
893 let lo = self.token.span;
895 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
896 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
897 || self.check(&token::BinOp(token::Star))
898 || self.is_import_coupler()
900 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
901 let mod_sep_ctxt = self.token.span.ctxt();
902 if self.eat(&token::ModSep) {
905 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
908 self.parse_use_tree_glob_or_nested()?
910 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
911 prefix = self.parse_path(PathStyle::Mod)?;
913 if self.eat(&token::ModSep) {
914 self.parse_use_tree_glob_or_nested()?
916 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
920 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
923 /// Parses `*` or `{...}`.
924 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
925 Ok(if self.eat(&token::BinOp(token::Star)) {
928 UseTreeKind::Nested(self.parse_use_tree_list()?)
932 /// Parses a `UseTreeKind::Nested(list)`.
935 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
937 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
938 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
942 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
943 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
946 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
947 match self.token.ident() {
948 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
952 _ => self.parse_ident(),
956 /// Parses `extern crate` links.
960 /// ```ignore (illustrative)
961 /// extern crate foo;
962 /// extern crate bar as foo;
964 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
965 // Accept `extern crate name-like-this` for better diagnostics
966 let orig_name = self.parse_crate_name_with_dashes()?;
967 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
968 (rename, Some(orig_name.name))
973 Ok((item_name, ItemKind::ExternCrate(orig_name)))
976 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
977 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
978 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
980 let mut ident = if self.token.is_keyword(kw::SelfLower) {
981 self.parse_path_segment_ident()
985 let mut idents = vec![];
986 let mut replacement = vec![];
987 let mut fixed_crate_name = false;
988 // Accept `extern crate name-like-this` for better diagnostics.
989 let dash = token::BinOp(token::BinOpToken::Minus);
990 if self.token == dash {
991 // Do not include `-` as part of the expected tokens list.
992 while self.eat(&dash) {
993 fixed_crate_name = true;
994 replacement.push((self.prev_token.span, "_".to_string()));
995 idents.push(self.parse_ident()?);
998 if fixed_crate_name {
999 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1000 let mut fixed_name = ident.name.to_string();
1001 for part in idents {
1002 fixed_name.push_str(&format!("_{}", part.name));
1004 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1006 self.struct_span_err(fixed_name_sp, error_msg)
1007 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1008 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1014 /// Parses `extern` for foreign ABIs modules.
1016 /// `extern` is expected to have been consumed before calling this method.
1020 /// ```ignore (only-for-syntax-highlight)
1024 fn parse_item_foreign_mod(
1026 attrs: &mut Vec<Attribute>,
1027 mut unsafety: Unsafe,
1028 ) -> PResult<'a, ItemInfo> {
1029 let abi = self.parse_abi(); // ABI?
1030 if unsafety == Unsafe::No
1031 && self.token.is_keyword(kw::Unsafe)
1032 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1034 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1036 unsafety = Unsafe::Yes(self.token.span);
1037 self.eat_keyword(kw::Unsafe);
1039 let module = ast::ForeignMod {
1042 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1044 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1047 /// Parses a foreign item (one in an `extern { ... }` block).
1048 pub fn parse_foreign_item(
1050 force_collect: ForceCollect,
1051 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1052 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1053 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1054 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1055 let kind = match ForeignItemKind::try_from(kind) {
1057 Err(kind) => match kind {
1058 ItemKind::Const(_, a, b) => {
1059 self.error_on_foreign_const(span, ident);
1060 ForeignItemKind::Static(a, Mutability::Not, b)
1062 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1065 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1070 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1071 let span = self.sess.source_map().guess_head_span(span);
1072 let descr = kind.descr();
1073 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1074 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1079 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1080 self.struct_span_err(ident.span, "extern items cannot be `const`")
1082 span.with_hi(ident.span.lo()),
1083 "try using a static value",
1085 Applicability::MachineApplicable,
1087 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1091 fn is_unsafe_foreign_mod(&self) -> bool {
1092 self.token.is_keyword(kw::Unsafe)
1093 && self.is_keyword_ahead(1, &[kw::Extern])
1095 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1096 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1100 fn is_static_global(&mut self) -> bool {
1101 if self.check_keyword(kw::Static) {
1102 // Check if this could be a closure.
1103 !self.look_ahead(1, |token| {
1104 if token.is_keyword(kw::Move) {
1107 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1114 /// Recover on `const mut` with `const` already eaten.
1115 fn recover_const_mut(&mut self, const_span: Span) {
1116 if self.eat_keyword(kw::Mut) {
1117 let span = self.prev_token.span;
1118 self.struct_span_err(span, "const globals cannot be mutable")
1119 .span_label(span, "cannot be mutable")
1122 "you might want to declare a static instead",
1124 Applicability::MaybeIncorrect,
1130 /// Recover on `const impl` with `const` already eaten.
1131 fn recover_const_impl(
1134 attrs: &mut Vec<Attribute>,
1135 defaultness: Defaultness,
1136 ) -> PResult<'a, ItemInfo> {
1137 let impl_span = self.token.span;
1138 let mut err = self.expected_ident_found();
1140 // Only try to recover if this is implementing a trait for a type
1141 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1142 Ok(impl_info) => impl_info,
1143 Err(recovery_error) => {
1144 // Recovery failed, raise the "expected identifier" error
1145 recovery_error.cancel();
1151 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1152 *constness = Const::Yes(const_span);
1154 let before_trait = trai.path.span.shrink_to_lo();
1155 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1156 err.multipart_suggestion(
1157 "you might have meant to write a const trait impl",
1158 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1159 Applicability::MaybeIncorrect,
1163 ItemKind::Impl { .. } => return Err(err),
1164 _ => unreachable!(),
1170 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1171 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1173 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1174 fn parse_item_global(
1176 m: Option<Mutability>,
1177 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1178 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1180 // Parse the type of a `const` or `static mut?` item.
1181 // That is, the `":" $ty` fragment.
1182 let ty = if self.eat(&token::Colon) {
1185 self.recover_missing_const_type(id, m)
1188 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1189 self.expect_semi()?;
1193 /// We were supposed to parse `:` but the `:` was missing.
1194 /// This means that the type is missing.
1195 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1196 // Construct the error and stash it away with the hope
1197 // that typeck will later enrich the error with a type.
1198 let kind = match m {
1199 Some(Mutability::Mut) => "static mut",
1200 Some(Mutability::Not) => "static",
1203 let mut err = self.struct_span_err(id.span, &format!("missing type for `{kind}` item"));
1204 err.span_suggestion(
1206 "provide a type for the item",
1207 format!("{id}: <type>"),
1208 Applicability::HasPlaceholders,
1210 err.stash(id.span, StashKey::ItemNoType);
1212 // The user intended that the type be inferred,
1213 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1214 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None })
1217 /// Parses an enum declaration.
1218 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1219 let id = self.parse_ident()?;
1220 let mut generics = self.parse_generics()?;
1221 generics.where_clause = self.parse_where_clause()?;
1223 let (variants, _) = self
1224 .parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant())
1226 self.recover_stmt();
1230 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1231 Ok((id, ItemKind::Enum(enum_definition, generics)))
1234 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1235 let variant_attrs = self.parse_outer_attributes()?;
1236 self.collect_tokens_trailing_token(
1239 |this, variant_attrs| {
1240 let vlo = this.token.span;
1242 let vis = this.parse_visibility(FollowedByType::No)?;
1243 if !this.recover_nested_adt_item(kw::Enum)? {
1244 return Ok((None, TrailingToken::None));
1246 let ident = this.parse_field_ident("enum", vlo)?;
1248 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1249 // Parse a struct variant.
1250 let (fields, recovered) = this.parse_record_struct_body("struct", false)?;
1251 VariantData::Struct(fields, recovered)
1252 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1253 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1255 VariantData::Unit(DUMMY_NODE_ID)
1259 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1261 let vr = ast::Variant {
1265 attrs: variant_attrs.into(),
1268 span: vlo.to(this.prev_token.span),
1269 is_placeholder: false,
1272 Ok((Some(vr), TrailingToken::MaybeComma))
1277 /// Parses `struct Foo { ... }`.
1278 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1279 let class_name = self.parse_ident()?;
1281 let mut generics = self.parse_generics()?;
1283 // There is a special case worth noting here, as reported in issue #17904.
1284 // If we are parsing a tuple struct it is the case that the where clause
1285 // should follow the field list. Like so:
1287 // struct Foo<T>(T) where T: Copy;
1289 // If we are parsing a normal record-style struct it is the case
1290 // that the where clause comes before the body, and after the generics.
1291 // So if we look ahead and see a brace or a where-clause we begin
1292 // parsing a record style struct.
1294 // Otherwise if we look ahead and see a paren we parse a tuple-style
1297 let vdata = if self.token.is_keyword(kw::Where) {
1298 generics.where_clause = self.parse_where_clause()?;
1299 if self.eat(&token::Semi) {
1300 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1301 VariantData::Unit(DUMMY_NODE_ID)
1303 // If we see: `struct Foo<T> where T: Copy { ... }`
1304 let (fields, recovered) =
1305 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1306 VariantData::Struct(fields, recovered)
1308 // No `where` so: `struct Foo<T>;`
1309 } else if self.eat(&token::Semi) {
1310 VariantData::Unit(DUMMY_NODE_ID)
1311 // Record-style struct definition
1312 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1313 let (fields, recovered) =
1314 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1315 VariantData::Struct(fields, recovered)
1316 // Tuple-style struct definition with optional where-clause.
1317 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1318 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1319 generics.where_clause = self.parse_where_clause()?;
1320 self.expect_semi()?;
1323 let token_str = super::token_descr(&self.token);
1325 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1327 let mut err = self.struct_span_err(self.token.span, msg);
1328 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1332 Ok((class_name, ItemKind::Struct(vdata, generics)))
1335 /// Parses `union Foo { ... }`.
1336 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1337 let class_name = self.parse_ident()?;
1339 let mut generics = self.parse_generics()?;
1341 let vdata = if self.token.is_keyword(kw::Where) {
1342 generics.where_clause = self.parse_where_clause()?;
1343 let (fields, recovered) =
1344 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1345 VariantData::Struct(fields, recovered)
1346 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1347 let (fields, recovered) =
1348 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1349 VariantData::Struct(fields, recovered)
1351 let token_str = super::token_descr(&self.token);
1352 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1353 let mut err = self.struct_span_err(self.token.span, msg);
1354 err.span_label(self.token.span, "expected `where` or `{` after union name");
1358 Ok((class_name, ItemKind::Union(vdata, generics)))
1361 fn parse_record_struct_body(
1365 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1366 let mut fields = Vec::new();
1367 let mut recovered = false;
1368 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1369 while self.token != token::CloseDelim(Delimiter::Brace) {
1370 let field = self.parse_field_def(adt_ty).map_err(|e| {
1371 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1376 Ok(field) => fields.push(field),
1383 self.eat(&token::CloseDelim(Delimiter::Brace));
1385 let token_str = super::token_descr(&self.token);
1387 "expected {}`{{` after struct name, found {}",
1388 if parsed_where { "" } else { "`where`, or " },
1391 let mut err = self.struct_span_err(self.token.span, msg);
1395 "expected {}`{{` after struct name",
1396 if parsed_where { "" } else { "`where`, or " }
1402 Ok((fields, recovered))
1405 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1406 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1407 // Unit like structs are handled in parse_item_struct function
1408 self.parse_paren_comma_seq(|p| {
1409 let attrs = p.parse_outer_attributes()?;
1410 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1411 let lo = p.token.span;
1412 let vis = p.parse_visibility(FollowedByType::Yes)?;
1413 let ty = p.parse_ty()?;
1417 span: lo.to(ty.span),
1422 attrs: attrs.into(),
1423 is_placeholder: false,
1425 TrailingToken::MaybeComma,
1432 /// Parses an element of a struct declaration.
1433 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1434 let attrs = self.parse_outer_attributes()?;
1435 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1436 let lo = this.token.span;
1437 let vis = this.parse_visibility(FollowedByType::No)?;
1438 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1442 /// Parses a structure field declaration.
1443 fn parse_single_struct_field(
1448 attrs: Vec<Attribute>,
1449 ) -> PResult<'a, FieldDef> {
1450 let mut seen_comma: bool = false;
1451 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1452 if self.token == token::Comma {
1455 match self.token.kind {
1459 token::CloseDelim(Delimiter::Brace) => {}
1460 token::DocComment(..) => {
1461 let previous_span = self.prev_token.span;
1462 let mut err = self.span_err(self.token.span, Error::UselessDocComment);
1463 self.bump(); // consume the doc comment
1464 let comma_after_doc_seen = self.eat(&token::Comma);
1465 // `seen_comma` is always false, because we are inside doc block
1466 // condition is here to make code more readable
1467 if !seen_comma && comma_after_doc_seen {
1470 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1474 let sp = self.sess.source_map().next_point(previous_span);
1475 err.span_suggestion(
1477 "missing comma here",
1479 Applicability::MachineApplicable,
1486 let sp = self.prev_token.span.shrink_to_hi();
1487 let mut err = self.struct_span_err(
1489 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1492 // Try to recover extra trailing angle brackets
1493 let mut recovered = false;
1494 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1495 if let Some(last_segment) = segments.last() {
1496 recovered = self.check_trailing_angle_brackets(
1498 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1501 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1503 self.eat(&token::Comma);
1504 // `check_trailing_angle_brackets` already emitted a nicer error
1505 // NOTE(eddyb) this was `.cancel()`, but `err`
1506 // gets returned, so we can't fully defuse it.
1512 if self.token.is_ident() {
1513 // This is likely another field; emit the diagnostic and keep going
1514 err.span_suggestion(
1516 "try adding a comma",
1518 Applicability::MachineApplicable,
1525 // Make sure an error was emitted (either by recovering an angle bracket,
1526 // or by finding an identifier as the next token), since we're
1527 // going to continue parsing
1528 assert!(self.sess.span_diagnostic.has_errors().is_some());
1537 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1538 if let Err(mut err) = self.expect(&token::Colon) {
1539 let sm = self.sess.source_map();
1540 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1541 let semi_typo = self.token.kind == token::Semi
1542 && self.look_ahead(1, |t| {
1544 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1545 // when there's no type and `;` was used instead of a comma.
1546 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1547 (Ok(l), Ok(r)) => l.line == r.line,
1551 if eq_typo || semi_typo {
1553 // Gracefully handle small typos.
1554 err.span_suggestion_short(
1555 self.prev_token.span,
1556 "field names and their types are separated with `:`",
1558 Applicability::MachineApplicable,
1568 /// Parses a structure field.
1569 fn parse_name_and_ty(
1574 attrs: Vec<Attribute>,
1575 ) -> PResult<'a, FieldDef> {
1576 let name = self.parse_field_ident(adt_ty, lo)?;
1577 self.expect_field_ty_separator()?;
1578 let ty = self.parse_ty()?;
1579 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1580 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1581 .span_suggestion_verbose(
1583 "write a path separator here",
1585 Applicability::MaybeIncorrect,
1589 if self.token.kind == token::Eq {
1591 let const_expr = self.parse_anon_const_expr()?;
1592 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1593 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1596 "remove this unsupported default value",
1598 Applicability::MachineApplicable,
1603 span: lo.to(self.prev_token.span),
1608 attrs: attrs.into(),
1609 is_placeholder: false,
1613 /// Parses a field identifier. Specialized version of `parse_ident_common`
1614 /// for better diagnostics and suggestions.
1615 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1616 let (ident, is_raw) = self.ident_or_err()?;
1617 if !is_raw && ident.is_reserved() {
1618 let err = if self.check_fn_front_matter(false) {
1619 let inherited_vis = Visibility {
1620 span: rustc_span::DUMMY_SP,
1621 kind: VisibilityKind::Inherited,
1624 // We use `parse_fn` to get a span for the function
1625 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1626 if let Err(mut db) =
1627 self.parse_fn(&mut Vec::new(), fn_parse_mode, lo, &inherited_vis)
1631 let mut err = self.struct_span_err(
1632 lo.to(self.prev_token.span),
1633 &format!("functions are not allowed in {adt_ty} definitions"),
1635 err.help("unlike in C++, Java, and C#, functions are declared in `impl` blocks");
1636 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1639 self.expected_ident_found()
1647 /// Parses a declarative macro 2.0 definition.
1648 /// The `macro` keyword has already been parsed.
1650 /// MacBody = "{" TOKEN_STREAM "}" ;
1651 /// MacParams = "(" TOKEN_STREAM ")" ;
1652 /// DeclMac = "macro" Ident MacParams? MacBody ;
1654 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1655 let ident = self.parse_ident()?;
1656 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1657 self.parse_mac_args()? // `MacBody`
1658 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1659 let params = self.parse_token_tree(); // `MacParams`
1660 let pspan = params.span();
1661 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1662 return self.unexpected();
1664 let body = self.parse_token_tree(); // `MacBody`
1665 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1666 let bspan = body.span();
1667 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1668 let tokens = TokenStream::new(vec![params, arrow, body]);
1669 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1670 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1672 return self.unexpected();
1675 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1676 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1679 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1680 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1681 if self.check_keyword(kw::MacroRules) {
1682 let macro_rules_span = self.token.span;
1684 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1685 return IsMacroRulesItem::Yes { has_bang: true };
1686 } else if self.look_ahead(1, |t| (t.is_ident())) {
1688 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1693 Applicability::MachineApplicable,
1697 return IsMacroRulesItem::Yes { has_bang: false };
1701 IsMacroRulesItem::No
1704 /// Parses a `macro_rules! foo { ... }` declarative macro.
1705 fn parse_item_macro_rules(
1709 ) -> PResult<'a, ItemInfo> {
1710 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1713 self.expect(&token::Not)?; // `!`
1715 let ident = self.parse_ident()?;
1717 if self.eat(&token::Not) {
1718 // Handle macro_rules! foo!
1719 let span = self.prev_token.span;
1720 self.struct_span_err(span, "macro names aren't followed by a `!`")
1721 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1725 let body = self.parse_mac_args()?;
1726 self.eat_semi_for_macro_if_needed(&body);
1727 self.complain_if_pub_macro(vis, true);
1729 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1732 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1733 /// If that's not the case, emit an error.
1734 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1735 if let VisibilityKind::Inherited = vis.kind {
1739 let vstr = pprust::vis_to_string(vis);
1740 let vstr = vstr.trim_end();
1742 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1743 self.struct_span_err(vis.span, &msg)
1746 "try exporting the macro",
1748 Applicability::MaybeIncorrect, // speculative
1752 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1755 "remove the visibility",
1757 Applicability::MachineApplicable,
1759 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1764 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1765 if args.need_semicolon() && !self.eat(&token::Semi) {
1766 self.report_invalid_macro_expansion_item(args);
1770 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1771 let span = args.span().expect("undelimited macro call");
1772 let mut err = self.struct_span_err(
1774 "macros that expand to items must be delimited with braces or followed by a semicolon",
1776 // FIXME: This will make us not emit the help even for declarative
1777 // macros within the same crate (that we can fix), which is sad.
1778 if !span.from_expansion() {
1779 if self.unclosed_delims.is_empty() {
1780 let DelimSpan { open, close } = match args {
1781 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1782 MacArgs::Delimited(dspan, ..) => *dspan,
1784 err.multipart_suggestion(
1785 "change the delimiters to curly braces",
1786 vec![(open, "{".to_string()), (close, '}'.to_string())],
1787 Applicability::MaybeIncorrect,
1790 err.span_suggestion(
1792 "change the delimiters to curly braces",
1794 Applicability::HasPlaceholders,
1797 err.span_suggestion(
1798 span.shrink_to_hi(),
1801 Applicability::MaybeIncorrect,
1807 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1808 /// it is, we try to parse the item and report error about nested types.
1809 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1810 if (self.token.is_keyword(kw::Enum)
1811 || self.token.is_keyword(kw::Struct)
1812 || self.token.is_keyword(kw::Union))
1813 && self.look_ahead(1, |t| t.is_ident())
1815 let kw_token = self.token.clone();
1816 let kw_str = pprust::token_to_string(&kw_token);
1817 let item = self.parse_item(ForceCollect::No)?;
1819 self.struct_span_err(
1821 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
1825 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
1827 Applicability::MaybeIncorrect,
1830 // We successfully parsed the item but we must inform the caller about nested problem.
1837 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1839 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1841 /// This function pointer accepts an edition, because in edition 2015, trait declarations
1842 /// were allowed to omit parameter names. In 2018, they became required.
1843 type ReqName = fn(Edition) -> bool;
1845 /// Parsing configuration for functions.
1847 /// The syntax of function items is slightly different within trait definitions,
1848 /// impl blocks, and modules. It is still parsed using the same code, just with
1849 /// different flags set, so that even when the input is wrong and produces a parse
1850 /// error, it still gets into the AST and the rest of the parser and
1851 /// type checker can run.
1852 #[derive(Clone, Copy)]
1853 pub(crate) struct FnParseMode {
1854 /// A function pointer that decides if, per-parameter `p`, `p` must have a
1855 /// pattern or just a type. This field affects parsing of the parameters list.
1858 /// fn foo(alef: A) -> X { X::new() }
1859 /// -----^^ affects parsing this part of the function signature
1861 /// if req_name returns false, then this name is optional
1866 /// if req_name returns true, this is an error
1869 /// Calling this function pointer should only return false if:
1871 /// * The item is being parsed inside of a trait definition.
1872 /// Within an impl block or a module, it should always evaluate
1874 /// * The span is from Edition 2015. In particular, you can get a
1875 /// 2015 span inside a 2021 crate using macros.
1876 pub req_name: ReqName,
1877 /// If this flag is set to `true`, then plain, semicolon-terminated function
1878 /// prototypes are not allowed here.
1881 /// fn foo(alef: A) -> X { X::new() }
1884 /// this is always allowed
1886 /// fn bar(alef: A, bet: B) -> X;
1889 /// if req_body is set to true, this is an error
1892 /// This field should only be set to false if the item is inside of a trait
1893 /// definition or extern block. Within an impl block or a module, it should
1894 /// always be set to true.
1898 /// Parsing of functions and methods.
1899 impl<'a> Parser<'a> {
1900 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1903 attrs: &mut Vec<Attribute>,
1904 fn_parse_mode: FnParseMode,
1907 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1908 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
1909 let ident = self.parse_ident()?; // `foo`
1910 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1912 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1913 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1915 let mut sig_hi = self.prev_token.span;
1916 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
1917 let fn_sig_span = sig_lo.to(sig_hi);
1918 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1921 /// Parse the "body" of a function.
1922 /// This can either be `;` when there's no body,
1923 /// or e.g. a block when the function is a provided one.
1926 attrs: &mut Vec<Attribute>,
1930 ) -> PResult<'a, Option<P<Block>>> {
1931 let has_semi = if req_body {
1932 self.token.kind == TokenKind::Semi
1934 // Only include `;` in list of expected tokens if body is not required
1935 self.check(&TokenKind::Semi)
1937 let (inner_attrs, body) = if has_semi {
1938 // Include the trailing semicolon in the span of the signature
1939 self.expect_semi()?;
1940 *sig_hi = self.prev_token.span;
1942 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
1943 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1944 } else if self.token.kind == token::Eq {
1945 // Recover `fn foo() = $expr;`.
1947 let eq_sp = self.prev_token.span;
1948 let _ = self.parse_expr()?;
1949 self.expect_semi()?; // `;`
1950 let span = eq_sp.to(self.prev_token.span);
1951 self.struct_span_err(span, "function body cannot be `= expression;`")
1952 .multipart_suggestion(
1953 "surround the expression with `{` and `}` instead of `=` and `;`",
1954 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1955 Applicability::MachineApplicable,
1958 (Vec::new(), Some(self.mk_block_err(span)))
1960 let expected = if req_body {
1961 &[token::OpenDelim(Delimiter::Brace)][..]
1963 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
1965 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
1966 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
1967 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1968 // the AST for typechecking.
1969 err.span_label(ident.span, "while parsing this `fn`");
1977 attrs.extend(inner_attrs);
1981 /// Is the current token the start of an `FnHeader` / not a valid parse?
1983 /// `check_pub` adds additional `pub` to the checks in case users place it
1984 /// wrongly, can be used to ensure `pub` never comes after `default`.
1985 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
1986 // We use an over-approximation here.
1987 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1988 // `pub` is added in case users got confused with the ordering like `async pub fn`,
1989 // only if it wasn't preceded by `default` as `default pub` is invalid.
1990 let quals: &[Symbol] = if check_pub {
1991 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1993 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1995 self.check_keyword(kw::Fn) // Definitely an `fn`.
1996 // `$qual fn` or `$qual $qual`:
1997 || quals.iter().any(|&kw| self.check_keyword(kw))
1998 && self.look_ahead(1, |t| {
1999 // `$qual fn`, e.g. `const fn` or `async fn`.
2000 t.is_keyword(kw::Fn)
2001 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2002 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
2003 // Rule out 2015 `const async: T = val`.
2005 // Rule out unsafe extern block.
2006 && !self.is_unsafe_foreign_mod())
2009 || self.check_keyword(kw::Extern)
2010 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2011 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
2014 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2015 /// up to and including the `fn` keyword. The formal grammar is:
2018 /// Extern = "extern" StringLit? ;
2019 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2020 /// FnFrontMatter = FnQual "fn" ;
2023 /// `vis` represents the visibility that was already parsed, if any. Use
2024 /// `Visibility::Inherited` when no visibility is known.
2025 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2026 let sp_start = self.token.span;
2027 let constness = self.parse_constness();
2029 let async_start_sp = self.token.span;
2030 let asyncness = self.parse_asyncness();
2032 let unsafe_start_sp = self.token.span;
2033 let unsafety = self.parse_unsafety();
2035 let ext_start_sp = self.token.span;
2036 let ext = self.parse_extern();
2038 if let Async::Yes { span, .. } = asyncness {
2039 self.ban_async_in_2015(span);
2042 if !self.eat_keyword(kw::Fn) {
2043 // It is possible for `expect_one_of` to recover given the contents of
2044 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2045 // account for this.
2046 match self.expect_one_of(&[], &[]) {
2048 Ok(false) => unreachable!(),
2050 // Qualifier keywords ordering check
2056 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2057 // that the keyword is already present and the second instance should be removed.
2058 let wrong_kw = if self.check_keyword(kw::Const) {
2060 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2061 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2063 } else if self.check_keyword(kw::Async) {
2065 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2066 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2068 } else if self.check_keyword(kw::Unsafe) {
2070 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2071 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2077 // The keyword is already present, suggest removal of the second instance
2078 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2079 let original_kw = self
2080 .span_to_snippet(original_sp)
2081 .expect("Span extracted directly from keyword should always work");
2083 err.span_suggestion(
2084 self.token.uninterpolated_span(),
2085 &format!("`{original_kw}` already used earlier, remove this one"),
2087 Applicability::MachineApplicable,
2089 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2091 // The keyword has not been seen yet, suggest correct placement in the function front matter
2092 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2093 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2094 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2095 let misplaced_qual_sp = self.token.uninterpolated_span();
2096 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2098 err.span_suggestion(
2099 correct_pos_sp.to(misplaced_qual_sp),
2100 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2101 format!("{misplaced_qual} {current_qual}"),
2102 Applicability::MachineApplicable,
2103 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2106 // Recover incorrect visibility order such as `async pub`
2107 else if self.check_keyword(kw::Pub) {
2108 let sp = sp_start.to(self.prev_token.span);
2109 if let Ok(snippet) = self.span_to_snippet(sp) {
2110 let current_vis = match self.parse_visibility(FollowedByType::No) {
2117 let vs = pprust::vis_to_string(¤t_vis);
2118 let vs = vs.trim_end();
2120 // There was no explicit visibility
2121 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2122 err.span_suggestion(
2123 sp_start.to(self.prev_token.span),
2124 &format!("visibility `{vs}` must come before `{snippet}`"),
2125 format!("{vs} {snippet}"),
2126 Applicability::MachineApplicable,
2129 // There was an explicit visibility
2131 err.span_suggestion(
2133 "there is already a visibility modifier, remove one",
2135 Applicability::MachineApplicable,
2137 .span_note(orig_vis.span, "explicit visibility first seen here");
2146 Ok(FnHeader { constness, unsafety, asyncness, ext })
2149 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2150 fn ban_async_in_2015(&self, span: Span) {
2151 if span.rust_2015() {
2152 let diag = self.diagnostic();
2153 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2154 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2155 .help_use_latest_edition()
2160 /// Parses the parameter list and result type of a function declaration.
2161 pub(super) fn parse_fn_decl(
2164 ret_allow_plus: AllowPlus,
2165 recover_return_sign: RecoverReturnSign,
2166 ) -> PResult<'a, P<FnDecl>> {
2168 inputs: self.parse_fn_params(req_name)?,
2169 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2173 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2174 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2175 let mut first_param = true;
2176 // Parse the arguments, starting out with `self` being allowed...
2177 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2178 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2180 let lo = p.prev_token.span;
2181 // Skip every token until next possible arg or end.
2182 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2183 // Create a placeholder argument for proper arg count (issue #34264).
2184 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2186 // ...now that we've parsed the first argument, `self` is no longer allowed.
2187 first_param = false;
2190 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2191 self.deduplicate_recovered_params_names(&mut params);
2195 /// Parses a single function parameter.
2197 /// - `self` is syntactically allowed when `first_param` holds.
2198 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2199 let lo = self.token.span;
2200 let attrs = self.parse_outer_attributes()?;
2201 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2202 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2203 if let Some(mut param) = this.parse_self_param()? {
2204 param.attrs = attrs.into();
2205 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2206 return Ok((res?, TrailingToken::None));
2209 let is_name_required = match this.token.kind {
2210 token::DotDotDot => false,
2211 _ => req_name(this.token.span.edition()),
2213 let (pat, ty) = if is_name_required || this.is_named_param() {
2214 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2216 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2218 let mut err = this.unexpected::<()>().unwrap_err();
2219 return if let Some(ident) =
2220 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2223 Ok((dummy_arg(ident), TrailingToken::None))
2229 this.eat_incorrect_doc_comment_for_param_type();
2230 (pat, this.parse_ty_for_param()?)
2232 debug!("parse_param_general ident_to_pat");
2233 let parser_snapshot_before_ty = this.clone();
2234 this.eat_incorrect_doc_comment_for_param_type();
2235 let mut ty = this.parse_ty_for_param();
2237 && this.token != token::Comma
2238 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2240 // This wasn't actually a type, but a pattern looking like a type,
2241 // so we are going to rollback and re-parse for recovery.
2242 ty = this.unexpected();
2246 let ident = Ident::new(kw::Empty, this.prev_token.span);
2247 let bm = BindingMode::ByValue(Mutability::Not);
2248 let pat = this.mk_pat_ident(ty.span, bm, ident);
2251 // If this is a C-variadic argument and we hit an error, return the error.
2252 Err(err) if this.token == token::DotDotDot => return Err(err),
2253 // Recover from attempting to parse the argument as a type without pattern.
2256 *this = parser_snapshot_before_ty;
2257 this.recover_arg_parse()?
2262 let span = lo.until(this.token.span);
2266 attrs: attrs.into(),
2267 id: ast::DUMMY_NODE_ID,
2268 is_placeholder: false,
2273 TrailingToken::None,
2278 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2279 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2280 // Extract an identifier *after* having confirmed that the token is one.
2281 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2282 Some((ident, false)) => {
2286 _ => unreachable!(),
2288 // Is `self` `n` tokens ahead?
2289 let is_isolated_self = |this: &Self, n| {
2290 this.is_keyword_ahead(n, &[kw::SelfLower])
2291 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2293 // Is `mut self` `n` tokens ahead?
2294 let is_isolated_mut_self =
2295 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2296 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2297 let parse_self_possibly_typed = |this: &mut Self, m| {
2298 let eself_ident = expect_self_ident(this);
2299 let eself_hi = this.prev_token.span;
2300 let eself = if this.eat(&token::Colon) {
2301 SelfKind::Explicit(this.parse_ty()?, m)
2305 Ok((eself, eself_ident, eself_hi))
2307 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2308 let recover_self_ptr = |this: &mut Self| {
2309 let msg = "cannot pass `self` by raw pointer";
2310 let span = this.token.span;
2311 this.struct_span_err(span, msg).span_label(span, msg).emit();
2313 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2316 // Parse optional `self` parameter of a method.
2317 // Only a limited set of initial token sequences is considered `self` parameters; anything
2318 // else is parsed as a normal function parameter list, so some lookahead is required.
2319 let eself_lo = self.token.span;
2320 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2321 token::BinOp(token::And) => {
2322 let eself = if is_isolated_self(self, 1) {
2325 SelfKind::Region(None, Mutability::Not)
2326 } else if is_isolated_mut_self(self, 1) {
2330 SelfKind::Region(None, Mutability::Mut)
2331 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2334 let lt = self.expect_lifetime();
2335 SelfKind::Region(Some(lt), Mutability::Not)
2336 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2339 let lt = self.expect_lifetime();
2341 SelfKind::Region(Some(lt), Mutability::Mut)
2346 (eself, expect_self_ident(self), self.prev_token.span)
2349 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2351 recover_self_ptr(self)?
2353 // `*mut self` and `*const self`
2354 token::BinOp(token::Star)
2355 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2359 recover_self_ptr(self)?
2361 // `self` and `self: TYPE`
2362 token::Ident(..) if is_isolated_self(self, 0) => {
2363 parse_self_possibly_typed(self, Mutability::Not)?
2365 // `mut self` and `mut self: TYPE`
2366 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2368 parse_self_possibly_typed(self, Mutability::Mut)?
2370 _ => return Ok(None),
2373 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2374 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2377 fn is_named_param(&self) -> bool {
2378 let offset = match self.token.kind {
2379 token::Interpolated(ref nt) => match **nt {
2380 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2383 token::BinOp(token::And) | token::AndAnd => 1,
2384 _ if self.token.is_keyword(kw::Mut) => 1,
2388 self.look_ahead(offset, |t| t.is_ident())
2389 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2392 fn recover_first_param(&mut self) -> &'static str {
2394 .parse_outer_attributes()
2395 .and_then(|_| self.parse_self_param())
2396 .map_err(|e| e.cancel())
2398 Ok(Some(_)) => "method",
2404 enum IsMacroRulesItem {
2405 Yes { has_bang: bool },