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, 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, ErrorGuaranteed, PResult, StashKey};
17 use rustc_span::edition::{Edition, LATEST_STABLE_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};
22 use std::convert::TryFrom;
27 /// Parses a source module as a crate. This is the main entry point for the parser.
28 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
29 let (attrs, items, span) = self.parse_mod(&token::Eof)?;
30 Ok(ast::Crate { attrs, items, span, id: DUMMY_NODE_ID, is_placeholder: false })
33 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
34 fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
35 let unsafety = self.parse_unsafety();
36 self.expect_keyword(kw::Mod)?;
37 let id = self.parse_ident()?;
38 let mod_kind = if self.eat(&token::Semi) {
41 self.expect(&token::OpenDelim(token::Brace))?;
42 let (mut inner_attrs, items, inner_span) =
43 self.parse_mod(&token::CloseDelim(token::Brace))?;
44 attrs.append(&mut inner_attrs);
45 ModKind::Loaded(items, Inline::Yes, inner_span)
47 Ok((id, ItemKind::Mod(unsafety, mod_kind)))
50 /// Parses the contents of a module (inner attributes followed by module items).
54 ) -> PResult<'a, (Vec<Attribute>, Vec<P<Item>>, Span)> {
55 let lo = self.token.span;
56 let attrs = self.parse_inner_attributes()?;
58 let mut items = vec![];
59 while let Some(item) = self.parse_item(ForceCollect::No)? {
61 self.maybe_consume_incorrect_semicolon(&items);
65 let token_str = super::token_descr(&self.token);
66 if !self.maybe_consume_incorrect_semicolon(&items) {
67 let msg = &format!("expected item, found {}", token_str);
68 let mut err = self.struct_span_err(self.token.span, msg);
69 err.span_label(self.token.span, "expected item");
74 Ok((attrs, items, lo.to(self.prev_token.span)))
78 pub(super) type ItemInfo = (Ident, ItemKind);
81 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
82 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
83 self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
88 fn_parse_mode: FnParseMode,
89 force_collect: ForceCollect,
90 ) -> PResult<'a, Option<Item>> {
91 let attrs = self.parse_outer_attributes()?;
92 self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
95 pub(super) fn parse_item_common(
100 fn_parse_mode: FnParseMode,
101 force_collect: ForceCollect,
102 ) -> PResult<'a, Option<Item>> {
103 // Don't use `maybe_whole` so that we have precise control
104 // over when we bump the parser
105 if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
106 let mut item = item.clone();
109 attrs.prepend_to_nt_inner(&mut item.attrs);
110 return Ok(Some(item.into_inner()));
113 let mut unclosed_delims = vec![];
115 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
117 this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
118 unclosed_delims.append(&mut this.unclosed_delims);
119 Ok((item?, TrailingToken::None))
122 self.unclosed_delims.append(&mut unclosed_delims);
126 fn parse_item_common_(
128 mut attrs: Vec<Attribute>,
131 fn_parse_mode: FnParseMode,
132 ) -> PResult<'a, Option<Item>> {
133 let lo = self.token.span;
134 let vis = self.parse_visibility(FollowedByType::No)?;
135 let mut def = self.parse_defaultness();
137 self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, fn_parse_mode)?;
138 if let Some((ident, kind)) = kind {
139 self.error_on_unconsumed_default(def, &kind);
140 let span = lo.to(self.prev_token.span);
141 let id = DUMMY_NODE_ID;
142 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
143 return Ok(Some(item));
146 // At this point, we have failed to parse an item.
147 self.error_on_unmatched_vis(&vis);
148 self.error_on_unmatched_defaultness(def);
150 self.recover_attrs_no_item(&attrs)?;
155 /// Error in-case a non-inherited visibility was parsed but no item followed.
156 fn error_on_unmatched_vis(&self, vis: &Visibility) {
157 if let VisibilityKind::Inherited = vis.kind {
160 let vs = pprust::vis_to_string(&vis);
161 let vs = vs.trim_end();
162 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
163 .span_label(vis.span, "the visibility")
164 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
168 /// Error in-case a `default` was parsed but no item followed.
169 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
170 if let Defaultness::Default(sp) = def {
171 self.struct_span_err(sp, "`default` is not followed by an item")
172 .span_label(sp, "the `default` qualifier")
173 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
178 /// Error in-case `default` was parsed in an in-appropriate context.
179 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
180 if let Defaultness::Default(span) = def {
181 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
182 self.struct_span_err(span, &msg)
183 .span_label(span, "`default` because of this")
184 .note("only associated `fn`, `const`, and `type` items can be `default`")
189 /// Parses one of the items allowed by the flags.
192 attrs: &mut Vec<Attribute>,
193 macros_allowed: bool,
196 def: &mut Defaultness,
197 fn_parse_mode: FnParseMode,
198 ) -> PResult<'a, Option<ItemInfo>> {
199 let def_final = def == &Defaultness::Final;
200 let mut def = || mem::replace(def, Defaultness::Final);
202 let info = if self.eat_keyword(kw::Use) {
204 let tree = self.parse_use_tree()?;
206 // If wildcard or glob-like brace syntax doesn't have `;`,
207 // the user may not know `*` or `{}` should be the last.
208 if let Err(mut e) = self.expect_semi() {
210 UseTreeKind::Glob => {
211 e.note("the wildcard token must be last on the path").emit();
213 UseTreeKind::Nested(..) => {
214 e.note("glob-like brace syntax must be last on the path").emit();
221 (Ident::empty(), ItemKind::Use(tree))
222 } else if self.check_fn_front_matter(def_final) {
224 let (ident, sig, generics, body) = self.parse_fn(attrs, fn_parse_mode, lo, vis)?;
225 (ident, ItemKind::Fn(Box::new(Fn { defaultness: def(), sig, generics, body })))
226 } else if self.eat_keyword(kw::Extern) {
227 if self.eat_keyword(kw::Crate) {
229 self.parse_item_extern_crate()?
232 self.parse_item_foreign_mod(attrs, Unsafe::No)?
234 } else if self.is_unsafe_foreign_mod() {
236 let unsafety = self.parse_unsafety();
237 self.expect_keyword(kw::Extern)?;
238 self.parse_item_foreign_mod(attrs, unsafety)?
239 } else if self.is_static_global() {
241 self.bump(); // `static`
242 let m = self.parse_mutability();
243 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
244 (ident, ItemKind::Static(ty, m, expr))
245 } else if let Const::Yes(const_span) = self.parse_constness() {
247 if self.token.is_keyword(kw::Impl) {
248 // recover from `const impl`, suggest `impl const`
249 self.recover_const_impl(const_span, attrs, def())?
251 self.recover_const_mut(const_span);
252 let (ident, ty, expr) = self.parse_item_global(None)?;
253 (ident, ItemKind::Const(def(), ty, expr))
255 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
257 self.parse_item_trait(attrs, lo)?
258 } else if self.check_keyword(kw::Impl)
259 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
262 self.parse_item_impl(attrs, def())?
263 } else if self.check_keyword(kw::Mod)
264 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
267 self.parse_item_mod(attrs)?
268 } else if self.eat_keyword(kw::Type) {
270 self.parse_type_alias(def())?
271 } else if self.eat_keyword(kw::Enum) {
273 self.parse_item_enum()?
274 } else if self.eat_keyword(kw::Struct) {
276 self.parse_item_struct()?
277 } else if self.is_kw_followed_by_ident(kw::Union) {
279 self.bump(); // `union`
280 self.parse_item_union()?
281 } else if self.eat_keyword(kw::Macro) {
283 self.parse_item_decl_macro(lo)?
284 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
286 self.parse_item_macro_rules(vis, has_bang)?
287 } else if vis.kind.is_pub() && self.isnt_macro_invocation() {
288 self.recover_missing_kw_before_item()?;
290 } else if macros_allowed && self.check_path() {
291 // MACRO INVOCATION ITEM
292 (Ident::empty(), ItemKind::MacCall(self.parse_item_macro(vis)?))
299 /// When parsing a statement, would the start of a path be an item?
300 pub(super) fn is_path_start_item(&mut self) -> bool {
301 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
302 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
303 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
304 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
305 || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
308 /// Are we sure this could not possibly be a macro invocation?
309 fn isnt_macro_invocation(&mut self) -> bool {
310 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
313 /// Recover on encountering a struct or method definition where the user
314 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
315 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
316 // Space between `pub` keyword and the identifier
319 // ^^^ `sp` points here
320 let sp = self.prev_token.span.between(self.token.span);
321 let full_sp = self.prev_token.span.to(self.token.span);
322 let ident_sp = self.token.span;
323 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
324 // possible public struct definition where `struct` was forgotten
325 let ident = self.parse_ident().unwrap();
326 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
327 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
328 err.span_suggestion_short(
332 Applicability::MaybeIncorrect, // speculative
335 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
336 let ident = self.parse_ident().unwrap();
338 let kw_name = self.recover_first_param();
339 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
340 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
341 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
343 ("fn", kw_name, false)
344 } else if self.check(&token::OpenDelim(token::Brace)) {
346 ("fn", kw_name, false)
347 } else if self.check(&token::Colon) {
351 ("fn` or `struct", "function or struct", true)
354 let msg = format!("missing `{}` for {} definition", kw, kw_name);
355 let mut err = self.struct_span_err(sp, &msg);
357 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
359 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
360 err.span_suggestion_short(
364 Applicability::MachineApplicable,
366 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
369 "if you meant to call a macro, try",
370 format!("{}!", snippet),
371 // this is the `ambiguous` conditional branch
372 Applicability::MaybeIncorrect,
376 "if you meant to call a macro, remove the `pub` \
377 and add a trailing `!` after the identifier",
381 } else if self.look_ahead(1, |t| *t == token::Lt) {
382 let ident = self.parse_ident().unwrap();
383 self.eat_to_tokens(&[&token::Gt]);
385 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
386 ("fn", self.recover_first_param(), false)
387 } else if self.check(&token::OpenDelim(token::Brace)) {
388 ("struct", "struct", false)
390 ("fn` or `struct", "function or struct", true)
392 let msg = format!("missing `{}` for {} definition", kw, kw_name);
393 let mut err = self.struct_span_err(sp, &msg);
395 err.span_suggestion_short(
397 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
399 Applicability::MachineApplicable,
408 /// Parses an item macro, e.g., `item!();`.
409 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
410 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
411 self.expect(&token::Not)?; // `!`
412 match self.parse_mac_args() {
413 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
415 self.eat_semi_for_macro_if_needed(&args);
416 self.complain_if_pub_macro(vis, false);
417 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
421 // Maybe the user misspelled `macro_rules` (issue #91227)
422 if self.token.is_ident()
423 && path.segments.len() == 1
424 && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
428 "perhaps you meant to define a macro",
429 "macro_rules".to_string(),
430 Applicability::MachineApplicable,
438 /// Recover if we parsed attributes and expected an item but there was none.
439 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
440 let ([start @ end] | [start, .., end]) = attrs else {
443 let msg = if end.is_doc_comment() {
444 "expected item after doc comment"
446 "expected item after attributes"
448 let mut err = self.struct_span_err(end.span, msg);
449 if end.is_doc_comment() {
450 err.span_label(end.span, "this doc comment doesn't document anything");
452 if let [.., penultimate, _] = attrs {
453 err.span_label(start.span.to(penultimate.span), "other attributes here");
458 fn is_async_fn(&self) -> bool {
459 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
462 fn parse_polarity(&mut self) -> ast::ImplPolarity {
463 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
464 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
466 ast::ImplPolarity::Negative(self.prev_token.span)
468 ast::ImplPolarity::Positive
472 /// Parses an implementation item.
475 /// impl<'a, T> TYPE { /* impl items */ }
476 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
477 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
478 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
481 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
483 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
484 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
488 attrs: &mut Vec<Attribute>,
489 defaultness: Defaultness,
490 ) -> PResult<'a, ItemInfo> {
491 let unsafety = self.parse_unsafety();
492 self.expect_keyword(kw::Impl)?;
494 // First, parse generic parameters if necessary.
495 let mut generics = if self.choose_generics_over_qpath(0) {
496 self.parse_generics()?
498 let mut generics = Generics::default();
500 // /\ this is where `generics.span` should point when there are no type params.
501 generics.span = self.prev_token.span.shrink_to_hi();
505 let constness = self.parse_constness();
506 if let Const::Yes(span) = constness {
507 self.sess.gated_spans.gate(sym::const_trait_impl, span);
510 let polarity = self.parse_polarity();
512 // Parse both types and traits as a type, then reinterpret if necessary.
513 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
514 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
516 let span = self.prev_token.span.between(self.token.span);
517 self.struct_span_err(span, "missing trait in a trait impl")
522 Applicability::HasPlaceholders,
525 span.to(self.token.span),
526 "for an inherent impl, drop this `for`",
528 Applicability::MaybeIncorrect,
532 kind: TyKind::Path(None, err_path(span)),
538 self.parse_ty_with_generics_recovery(&generics)?
541 // If `for` is missing we try to recover.
542 let has_for = self.eat_keyword(kw::For);
543 let missing_for_span = self.prev_token.span.between(self.token.span);
545 let ty_second = if self.token == token::DotDot {
546 // We need to report this error after `cfg` expansion for compatibility reasons
547 self.bump(); // `..`, do not add it to expected tokens
548 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
549 } else if has_for || self.token.can_begin_type() {
550 Some(self.parse_ty()?)
555 generics.where_clause = self.parse_where_clause()?;
557 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
559 let item_kind = match ty_second {
561 // impl Trait for Type
563 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
564 .span_suggestion_short(
568 Applicability::MachineApplicable,
573 let ty_first = ty_first.into_inner();
574 let path = match ty_first.kind {
575 // This notably includes paths passed through `ty` macro fragments (#46438).
576 TyKind::Path(None, path) => path,
578 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
579 err_path(ty_first.span)
582 let trait_ref = TraitRef { path, ref_id: ty_first.id };
584 ItemKind::Impl(Box::new(Impl {
590 of_trait: Some(trait_ref),
597 ItemKind::Impl(Box::new(Impl {
610 Ok((Ident::empty(), item_kind))
613 fn parse_item_list<T>(
615 attrs: &mut Vec<Attribute>,
616 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
617 ) -> PResult<'a, Vec<T>> {
618 let open_brace_span = self.token.span;
619 self.expect(&token::OpenDelim(token::Brace))?;
620 attrs.append(&mut self.parse_inner_attributes()?);
622 let mut items = Vec::new();
623 while !self.eat(&token::CloseDelim(token::Brace)) {
624 if self.recover_doc_comment_before_brace() {
627 match parse_item(self) {
629 // We have to bail or we'll potentially never make progress.
630 let non_item_span = self.token.span;
631 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
632 self.struct_span_err(non_item_span, "non-item in item list")
633 .span_label(open_brace_span, "item list starts here")
634 .span_label(non_item_span, "non-item starts here")
635 .span_label(self.prev_token.span, "item list ends here")
639 Ok(Some(item)) => items.extend(item),
641 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
642 err.span_label(open_brace_span, "while parsing this item list starting here")
643 .span_label(self.prev_token.span, "the item list ends here")
652 /// Recover on a doc comment before `}`.
653 fn recover_doc_comment_before_brace(&mut self) -> bool {
654 if let token::DocComment(..) = self.token.kind {
655 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
660 "found a documentation comment that doesn't document anything",
662 .span_label(self.token.span, "this doc comment doesn't document anything")
664 "doc comments must come before what they document, maybe a \
665 comment was intended with `//`?",
675 /// Parses defaultness (i.e., `default` or nothing).
676 fn parse_defaultness(&mut self) -> Defaultness {
677 // We are interested in `default` followed by another identifier.
678 // However, we must avoid keywords that occur as binary operators.
679 // Currently, the only applicable keyword is `as` (`default as Ty`).
680 if self.check_keyword(kw::Default)
681 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
683 self.bump(); // `default`
684 Defaultness::Default(self.prev_token.uninterpolated_span())
690 /// Is this an `(unsafe auto? | auto) trait` item?
691 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
693 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
695 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
698 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
699 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
700 let unsafety = self.parse_unsafety();
701 // Parse optional `auto` prefix.
702 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
704 self.expect_keyword(kw::Trait)?;
705 let ident = self.parse_ident()?;
706 let mut generics = self.parse_generics()?;
708 // Parse optional colon and supertrait bounds.
709 let had_colon = self.eat(&token::Colon);
710 let span_at_colon = self.prev_token.span;
711 let bounds = if had_colon {
712 self.parse_generic_bounds(Some(self.prev_token.span))?
717 let span_before_eq = self.prev_token.span;
718 if self.eat(&token::Eq) {
719 // It's a trait alias.
721 let span = span_at_colon.to(span_before_eq);
722 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
725 let bounds = self.parse_generic_bounds(None)?;
726 generics.where_clause = self.parse_where_clause()?;
729 let whole_span = lo.to(self.prev_token.span);
730 if is_auto == IsAuto::Yes {
731 let msg = "trait aliases cannot be `auto`";
732 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
734 if let Unsafe::Yes(_) = unsafety {
735 let msg = "trait aliases cannot be `unsafe`";
736 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
739 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
741 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
743 // It's a normal trait.
744 generics.where_clause = self.parse_where_clause()?;
745 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
748 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
753 pub fn parse_impl_item(
755 force_collect: ForceCollect,
756 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
757 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
758 self.parse_assoc_item(fn_parse_mode, force_collect)
761 pub fn parse_trait_item(
763 force_collect: ForceCollect,
764 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
766 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
767 self.parse_assoc_item(fn_parse_mode, force_collect)
770 /// Parses associated items.
773 fn_parse_mode: FnParseMode,
774 force_collect: ForceCollect,
775 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
776 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
777 |Item { attrs, id, span, vis, ident, kind, tokens }| {
778 let kind = match AssocItemKind::try_from(kind) {
780 Err(kind) => match kind {
781 ItemKind::Static(a, _, b) => {
782 self.struct_span_err(span, "associated `static` items are not allowed")
784 AssocItemKind::Const(Defaultness::Final, a, b)
786 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
789 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
794 /// Emits an error that the where clause at the end of a type alias is not
795 /// allowed and suggests moving it.
796 fn error_ty_alias_where(
798 before_where_clause_present: bool,
799 before_where_clause_span: Span,
800 after_predicates: &[WherePredicate],
801 after_where_clause_span: Span,
802 ) -> ErrorGuaranteed {
804 self.struct_span_err(after_where_clause_span, "where clause not allowed here");
805 if !after_predicates.is_empty() {
806 let mut state = crate::pprust::State::new();
807 if !before_where_clause_present {
809 state.word_space("where");
811 state.word_space(",");
813 let mut first = true;
814 for p in after_predicates.iter() {
816 state.word_space(",");
819 state.print_where_predicate(p);
821 let suggestion = state.s.eof();
823 before_where_clause_span.shrink_to_hi(),
826 Applicability::MachineApplicable,
832 /// Parses a `type` alias with the following grammar:
834 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
836 /// The `"type"` has already been eaten.
837 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
838 let ident = self.parse_ident()?;
839 let mut generics = self.parse_generics()?;
841 // Parse optional colon and param bounds.
843 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
845 generics.where_clause = self.parse_where_clause()?;
847 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
849 if self.token.is_keyword(kw::Where) {
850 let after_where_clause = self.parse_where_clause()?;
852 self.error_ty_alias_where(
853 generics.where_clause.has_where_token,
854 generics.where_clause.span,
855 &after_where_clause.predicates,
856 after_where_clause.span,
859 generics.where_clause.predicates.extend(after_where_clause.predicates.into_iter());
864 Ok((ident, ItemKind::TyAlias(Box::new(TyAlias { defaultness, generics, bounds, ty }))))
867 /// Parses a `UseTree`.
870 /// USE_TREE = [`::`] `*` |
871 /// [`::`] `{` USE_TREE_LIST `}` |
873 /// PATH `::` `{` USE_TREE_LIST `}` |
874 /// PATH [`as` IDENT]
876 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
877 let lo = self.token.span;
879 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
880 let kind = if self.check(&token::OpenDelim(token::Brace))
881 || self.check(&token::BinOp(token::Star))
882 || self.is_import_coupler()
884 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
885 let mod_sep_ctxt = self.token.span.ctxt();
886 if self.eat(&token::ModSep) {
889 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
892 self.parse_use_tree_glob_or_nested()?
894 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
895 prefix = self.parse_path(PathStyle::Mod)?;
897 if self.eat(&token::ModSep) {
898 self.parse_use_tree_glob_or_nested()?
900 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
904 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
907 /// Parses `*` or `{...}`.
908 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
909 Ok(if self.eat(&token::BinOp(token::Star)) {
912 UseTreeKind::Nested(self.parse_use_tree_list()?)
916 /// Parses a `UseTreeKind::Nested(list)`.
919 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
921 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
922 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
926 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
927 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
930 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
931 match self.token.ident() {
932 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
936 _ => self.parse_ident(),
940 /// Parses `extern crate` links.
945 /// extern crate foo;
946 /// extern crate bar as foo;
948 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
949 // Accept `extern crate name-like-this` for better diagnostics
950 let orig_name = self.parse_crate_name_with_dashes()?;
951 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
952 (rename, Some(orig_name.name))
957 Ok((item_name, ItemKind::ExternCrate(orig_name)))
960 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
961 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
962 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
964 let mut ident = if self.token.is_keyword(kw::SelfLower) {
965 self.parse_path_segment_ident()
969 let mut idents = vec![];
970 let mut replacement = vec![];
971 let mut fixed_crate_name = false;
972 // Accept `extern crate name-like-this` for better diagnostics.
973 let dash = token::BinOp(token::BinOpToken::Minus);
974 if self.token == dash {
975 // Do not include `-` as part of the expected tokens list.
976 while self.eat(&dash) {
977 fixed_crate_name = true;
978 replacement.push((self.prev_token.span, "_".to_string()));
979 idents.push(self.parse_ident()?);
982 if fixed_crate_name {
983 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
984 let mut fixed_name = format!("{}", ident.name);
986 fixed_name.push_str(&format!("_{}", part.name));
988 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
990 self.struct_span_err(fixed_name_sp, error_msg)
991 .span_label(fixed_name_sp, "dash-separated idents are not valid")
992 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
998 /// Parses `extern` for foreign ABIs modules.
1000 /// `extern` is expected to have been consumed before calling this method.
1004 /// ```ignore (only-for-syntax-highlight)
1008 fn parse_item_foreign_mod(
1010 attrs: &mut Vec<Attribute>,
1012 ) -> PResult<'a, ItemInfo> {
1013 let abi = self.parse_abi(); // ABI?
1014 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?;
1015 let module = ast::ForeignMod { unsafety, abi, items };
1016 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1019 /// Parses a foreign item (one in an `extern { ... }` block).
1020 pub fn parse_foreign_item(
1022 force_collect: ForceCollect,
1023 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1024 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1025 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1026 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1027 let kind = match ForeignItemKind::try_from(kind) {
1029 Err(kind) => match kind {
1030 ItemKind::Const(_, a, b) => {
1031 self.error_on_foreign_const(span, ident);
1032 ForeignItemKind::Static(a, Mutability::Not, b)
1034 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1037 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1042 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1043 let span = self.sess.source_map().guess_head_span(span);
1044 let descr = kind.descr();
1045 self.struct_span_err(span, &format!("{} is not supported in {}", descr, ctx))
1046 .help(&format!("consider moving the {} out to a nearby module scope", descr))
1051 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1052 self.struct_span_err(ident.span, "extern items cannot be `const`")
1054 span.with_hi(ident.span.lo()),
1055 "try using a static value",
1056 "static ".to_string(),
1057 Applicability::MachineApplicable,
1059 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1063 fn is_unsafe_foreign_mod(&self) -> bool {
1064 self.token.is_keyword(kw::Unsafe)
1065 && self.is_keyword_ahead(1, &[kw::Extern])
1067 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1068 |t| t.kind == token::OpenDelim(token::Brace),
1072 fn is_static_global(&mut self) -> bool {
1073 if self.check_keyword(kw::Static) {
1074 // Check if this could be a closure.
1075 !self.look_ahead(1, |token| {
1076 if token.is_keyword(kw::Move) {
1079 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1086 /// Recover on `const mut` with `const` already eaten.
1087 fn recover_const_mut(&mut self, const_span: Span) {
1088 if self.eat_keyword(kw::Mut) {
1089 let span = self.prev_token.span;
1090 self.struct_span_err(span, "const globals cannot be mutable")
1091 .span_label(span, "cannot be mutable")
1094 "you might want to declare a static instead",
1095 "static".to_owned(),
1096 Applicability::MaybeIncorrect,
1102 /// Recover on `const impl` with `const` already eaten.
1103 fn recover_const_impl(
1106 attrs: &mut Vec<Attribute>,
1107 defaultness: Defaultness,
1108 ) -> PResult<'a, ItemInfo> {
1109 let impl_span = self.token.span;
1110 let mut err = self.expected_ident_found();
1112 // Only try to recover if this is implementing a trait for a type
1113 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1114 Ok(impl_info) => impl_info,
1115 Err(recovery_error) => {
1116 // Recovery failed, raise the "expected identifier" error
1117 recovery_error.cancel();
1123 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1124 *constness = Const::Yes(const_span);
1126 let before_trait = trai.path.span.shrink_to_lo();
1127 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1128 err.multipart_suggestion(
1129 "you might have meant to write a const trait impl",
1130 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1131 Applicability::MaybeIncorrect,
1135 ItemKind::Impl { .. } => return Err(err),
1136 _ => unreachable!(),
1142 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1143 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1145 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1146 fn parse_item_global(
1148 m: Option<Mutability>,
1149 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1150 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1152 // Parse the type of a `const` or `static mut?` item.
1153 // That is, the `":" $ty` fragment.
1154 let ty = if self.eat(&token::Colon) {
1157 self.recover_missing_const_type(id, m)
1160 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1161 self.expect_semi()?;
1165 /// We were supposed to parse `:` but the `:` was missing.
1166 /// This means that the type is missing.
1167 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1168 // Construct the error and stash it away with the hope
1169 // that typeck will later enrich the error with a type.
1170 let kind = match m {
1171 Some(Mutability::Mut) => "static mut",
1172 Some(Mutability::Not) => "static",
1175 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1176 err.span_suggestion(
1178 "provide a type for the item",
1179 format!("{}: <type>", id),
1180 Applicability::HasPlaceholders,
1182 err.stash(id.span, StashKey::ItemNoType);
1184 // The user intended that the type be inferred,
1185 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1186 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None })
1189 /// Parses an enum declaration.
1190 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1191 let id = self.parse_ident()?;
1192 let mut generics = self.parse_generics()?;
1193 generics.where_clause = self.parse_where_clause()?;
1196 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1197 self.recover_stmt();
1201 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1202 Ok((id, ItemKind::Enum(enum_definition, generics)))
1205 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1206 let variant_attrs = self.parse_outer_attributes()?;
1207 self.collect_tokens_trailing_token(
1210 |this, variant_attrs| {
1211 let vlo = this.token.span;
1213 let vis = this.parse_visibility(FollowedByType::No)?;
1214 if !this.recover_nested_adt_item(kw::Enum)? {
1215 return Ok((None, TrailingToken::None));
1217 let ident = this.parse_field_ident("enum", vlo)?;
1219 let struct_def = if this.check(&token::OpenDelim(token::Brace)) {
1220 // Parse a struct variant.
1221 let (fields, recovered) = this.parse_record_struct_body("struct", false)?;
1222 VariantData::Struct(fields, recovered)
1223 } else if this.check(&token::OpenDelim(token::Paren)) {
1224 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1226 VariantData::Unit(DUMMY_NODE_ID)
1230 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1232 let vr = ast::Variant {
1236 attrs: variant_attrs.into(),
1239 span: vlo.to(this.prev_token.span),
1240 is_placeholder: false,
1243 Ok((Some(vr), TrailingToken::MaybeComma))
1248 /// Parses `struct Foo { ... }`.
1249 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1250 let class_name = self.parse_ident()?;
1252 let mut generics = self.parse_generics()?;
1254 // There is a special case worth noting here, as reported in issue #17904.
1255 // If we are parsing a tuple struct it is the case that the where clause
1256 // should follow the field list. Like so:
1258 // struct Foo<T>(T) where T: Copy;
1260 // If we are parsing a normal record-style struct it is the case
1261 // that the where clause comes before the body, and after the generics.
1262 // So if we look ahead and see a brace or a where-clause we begin
1263 // parsing a record style struct.
1265 // Otherwise if we look ahead and see a paren we parse a tuple-style
1268 let vdata = if self.token.is_keyword(kw::Where) {
1269 generics.where_clause = self.parse_where_clause()?;
1270 if self.eat(&token::Semi) {
1271 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1272 VariantData::Unit(DUMMY_NODE_ID)
1274 // If we see: `struct Foo<T> where T: Copy { ... }`
1275 let (fields, recovered) =
1276 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1277 VariantData::Struct(fields, recovered)
1279 // No `where` so: `struct Foo<T>;`
1280 } else if self.eat(&token::Semi) {
1281 VariantData::Unit(DUMMY_NODE_ID)
1282 // Record-style struct definition
1283 } else if self.token == token::OpenDelim(token::Brace) {
1284 let (fields, recovered) =
1285 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1286 VariantData::Struct(fields, recovered)
1287 // Tuple-style struct definition with optional where-clause.
1288 } else if self.token == token::OpenDelim(token::Paren) {
1289 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1290 generics.where_clause = self.parse_where_clause()?;
1291 self.expect_semi()?;
1294 let token_str = super::token_descr(&self.token);
1296 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1299 let mut err = self.struct_span_err(self.token.span, msg);
1300 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1304 Ok((class_name, ItemKind::Struct(vdata, generics)))
1307 /// Parses `union Foo { ... }`.
1308 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1309 let class_name = self.parse_ident()?;
1311 let mut generics = self.parse_generics()?;
1313 let vdata = if self.token.is_keyword(kw::Where) {
1314 generics.where_clause = self.parse_where_clause()?;
1315 let (fields, recovered) =
1316 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1317 VariantData::Struct(fields, recovered)
1318 } else if self.token == token::OpenDelim(token::Brace) {
1319 let (fields, recovered) =
1320 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1321 VariantData::Struct(fields, recovered)
1323 let token_str = super::token_descr(&self.token);
1324 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1325 let mut err = self.struct_span_err(self.token.span, msg);
1326 err.span_label(self.token.span, "expected `where` or `{` after union name");
1330 Ok((class_name, ItemKind::Union(vdata, generics)))
1333 fn parse_record_struct_body(
1337 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1338 let mut fields = Vec::new();
1339 let mut recovered = false;
1340 if self.eat(&token::OpenDelim(token::Brace)) {
1341 while self.token != token::CloseDelim(token::Brace) {
1342 let field = self.parse_field_def(adt_ty).map_err(|e| {
1343 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1348 Ok(field) => fields.push(field),
1355 self.eat(&token::CloseDelim(token::Brace));
1357 let token_str = super::token_descr(&self.token);
1359 "expected {}`{{` after struct name, found {}",
1360 if parsed_where { "" } else { "`where`, or " },
1363 let mut err = self.struct_span_err(self.token.span, msg);
1367 "expected {}`{{` after struct name",
1368 if parsed_where { "" } else { "`where`, or " }
1374 Ok((fields, recovered))
1377 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1378 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1379 // Unit like structs are handled in parse_item_struct function
1380 self.parse_paren_comma_seq(|p| {
1381 let attrs = p.parse_outer_attributes()?;
1382 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1383 let lo = p.token.span;
1384 let vis = p.parse_visibility(FollowedByType::Yes)?;
1385 let ty = p.parse_ty()?;
1389 span: lo.to(ty.span),
1394 attrs: attrs.into(),
1395 is_placeholder: false,
1397 TrailingToken::MaybeComma,
1404 /// Parses an element of a struct declaration.
1405 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1406 let attrs = self.parse_outer_attributes()?;
1407 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1408 let lo = this.token.span;
1409 let vis = this.parse_visibility(FollowedByType::No)?;
1410 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1414 /// Parses a structure field declaration.
1415 fn parse_single_struct_field(
1420 attrs: Vec<Attribute>,
1421 ) -> PResult<'a, FieldDef> {
1422 let mut seen_comma: bool = false;
1423 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1424 if self.token == token::Comma {
1427 match self.token.kind {
1431 token::CloseDelim(token::Brace) => {}
1432 token::DocComment(..) => {
1433 let previous_span = self.prev_token.span;
1434 let mut err = self.span_err(self.token.span, Error::UselessDocComment);
1435 self.bump(); // consume the doc comment
1436 let comma_after_doc_seen = self.eat(&token::Comma);
1437 // `seen_comma` is always false, because we are inside doc block
1438 // condition is here to make code more readable
1439 if !seen_comma && comma_after_doc_seen {
1442 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1446 let sp = self.sess.source_map().next_point(previous_span);
1447 err.span_suggestion(
1449 "missing comma here",
1451 Applicability::MachineApplicable,
1458 let sp = self.prev_token.span.shrink_to_hi();
1459 let mut err = self.struct_span_err(
1461 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1464 // Try to recover extra trailing angle brackets
1465 let mut recovered = false;
1466 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1467 if let Some(last_segment) = segments.last() {
1468 recovered = self.check_trailing_angle_brackets(
1470 &[&token::Comma, &token::CloseDelim(token::Brace)],
1473 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1475 self.eat(&token::Comma);
1476 // `check_trailing_angle_brackets` already emitted a nicer error
1477 // NOTE(eddyb) this was `.cancel()`, but `err`
1478 // gets returned, so we can't fully defuse it.
1479 err.downgrade_to_delayed_bug();
1484 if self.token.is_ident() {
1485 // This is likely another field; emit the diagnostic and keep going
1486 err.span_suggestion(
1488 "try adding a comma",
1490 Applicability::MachineApplicable,
1497 // Make sure an error was emitted (either by recovering an angle bracket,
1498 // or by finding an identifier as the next token), since we're
1499 // going to continue parsing
1500 assert!(self.sess.span_diagnostic.has_errors());
1509 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1510 if let Err(mut err) = self.expect(&token::Colon) {
1511 let sm = self.sess.source_map();
1512 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1513 let semi_typo = self.token.kind == token::Semi
1514 && self.look_ahead(1, |t| {
1516 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1517 // when there's no type and `;` was used instead of a comma.
1518 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1519 (Ok(l), Ok(r)) => l.line == r.line,
1523 if eq_typo || semi_typo {
1525 // Gracefully handle small typos.
1526 err.span_suggestion_short(
1527 self.prev_token.span,
1528 "field names and their types are separated with `:`",
1530 Applicability::MachineApplicable,
1540 /// Parses a structure field.
1541 fn parse_name_and_ty(
1546 attrs: Vec<Attribute>,
1547 ) -> PResult<'a, FieldDef> {
1548 let name = self.parse_field_ident(adt_ty, lo)?;
1549 self.expect_field_ty_separator()?;
1550 let ty = self.parse_ty()?;
1551 if self.token.kind == token::Eq {
1553 let const_expr = self.parse_anon_const_expr()?;
1554 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1555 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1558 "remove this unsupported default value",
1560 Applicability::MachineApplicable,
1565 span: lo.to(self.prev_token.span),
1570 attrs: attrs.into(),
1571 is_placeholder: false,
1575 /// Parses a field identifier. Specialized version of `parse_ident_common`
1576 /// for better diagnostics and suggestions.
1577 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1578 let (ident, is_raw) = self.ident_or_err()?;
1579 if !is_raw && ident.is_reserved() {
1580 let err = if self.check_fn_front_matter(false) {
1581 let inherited_vis = Visibility {
1582 span: rustc_span::DUMMY_SP,
1583 kind: VisibilityKind::Inherited,
1586 // We use `parse_fn` to get a span for the function
1587 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1588 if let Err(mut db) =
1589 self.parse_fn(&mut Vec::new(), fn_parse_mode, lo, &inherited_vis)
1593 let mut err = self.struct_span_err(
1594 lo.to(self.prev_token.span),
1595 &format!("functions are not allowed in {} definitions", adt_ty),
1597 err.help("unlike in C++, Java, and C#, functions are declared in `impl` blocks");
1598 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1601 self.expected_ident_found()
1609 /// Parses a declarative macro 2.0 definition.
1610 /// The `macro` keyword has already been parsed.
1612 /// MacBody = "{" TOKEN_STREAM "}" ;
1613 /// MacParams = "(" TOKEN_STREAM ")" ;
1614 /// DeclMac = "macro" Ident MacParams? MacBody ;
1616 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1617 let ident = self.parse_ident()?;
1618 let body = if self.check(&token::OpenDelim(token::Brace)) {
1619 self.parse_mac_args()? // `MacBody`
1620 } else if self.check(&token::OpenDelim(token::Paren)) {
1621 let params = self.parse_token_tree(); // `MacParams`
1622 let pspan = params.span();
1623 if !self.check(&token::OpenDelim(token::Brace)) {
1624 return self.unexpected();
1626 let body = self.parse_token_tree(); // `MacBody`
1627 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1628 let bspan = body.span();
1629 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1630 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1631 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1632 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1634 return self.unexpected();
1637 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1638 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1641 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1643 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1644 if self.check_keyword(kw::MacroRules) {
1645 let macro_rules_span = self.token.span;
1647 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1648 return IsMacroRulesItem::Yes { has_bang: true };
1649 } else if self.look_ahead(1, |t| (t.is_ident())) {
1651 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1655 "macro_rules!".to_owned(),
1656 Applicability::MachineApplicable,
1660 return IsMacroRulesItem::Yes { has_bang: false };
1664 IsMacroRulesItem::No
1667 /// Parses a `macro_rules! foo { ... }` declarative macro.
1668 fn parse_item_macro_rules(
1672 ) -> PResult<'a, ItemInfo> {
1673 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1676 self.expect(&token::Not)?; // `!`
1678 let ident = self.parse_ident()?;
1680 if self.eat(&token::Not) {
1681 // Handle macro_rules! foo!
1682 let span = self.prev_token.span;
1683 self.struct_span_err(span, "macro names aren't followed by a `!`")
1688 Applicability::MachineApplicable,
1693 let body = self.parse_mac_args()?;
1694 self.eat_semi_for_macro_if_needed(&body);
1695 self.complain_if_pub_macro(vis, true);
1697 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1700 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1701 /// If that's not the case, emit an error.
1702 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1703 if let VisibilityKind::Inherited = vis.kind {
1707 let vstr = pprust::vis_to_string(vis);
1708 let vstr = vstr.trim_end();
1710 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1711 self.struct_span_err(vis.span, &msg)
1714 "try exporting the macro",
1715 "#[macro_export]".to_owned(),
1716 Applicability::MaybeIncorrect, // speculative
1720 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1723 "remove the visibility",
1725 Applicability::MachineApplicable,
1727 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1732 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1733 if args.need_semicolon() && !self.eat(&token::Semi) {
1734 self.report_invalid_macro_expansion_item(args);
1738 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1739 let span = args.span().expect("undelimited macro call");
1740 let mut err = self.struct_span_err(
1742 "macros that expand to items must be delimited with braces or followed by a semicolon",
1744 if self.unclosed_delims.is_empty() {
1745 let DelimSpan { open, close } = match args {
1746 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1747 MacArgs::Delimited(dspan, ..) => *dspan,
1749 err.multipart_suggestion(
1750 "change the delimiters to curly braces",
1751 vec![(open, "{".to_string()), (close, '}'.to_string())],
1752 Applicability::MaybeIncorrect,
1755 err.span_suggestion(
1757 "change the delimiters to curly braces",
1758 " { /* items */ }".to_string(),
1759 Applicability::HasPlaceholders,
1762 err.span_suggestion(
1763 span.shrink_to_hi(),
1766 Applicability::MaybeIncorrect,
1771 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1772 /// it is, we try to parse the item and report error about nested types.
1773 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1774 if (self.token.is_keyword(kw::Enum)
1775 || self.token.is_keyword(kw::Struct)
1776 || self.token.is_keyword(kw::Union))
1777 && self.look_ahead(1, |t| t.is_ident())
1779 let kw_token = self.token.clone();
1780 let kw_str = pprust::token_to_string(&kw_token);
1781 let item = self.parse_item(ForceCollect::No)?;
1783 self.struct_span_err(
1785 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1789 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1791 Applicability::MaybeIncorrect,
1794 // We successfully parsed the item but we must inform the caller about nested problem.
1801 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1803 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1805 /// This function pointer accepts an edition, because in edition 2015, trait declarations
1806 /// were allowed to omit parameter names. In 2018, they became required.
1807 type ReqName = fn(Edition) -> bool;
1809 /// Parsing configuration for functions.
1811 /// The syntax of function items is slightly different within trait definitions,
1812 /// impl blocks, and modules. It is still parsed using the same code, just with
1813 /// different flags set, so that even when the input is wrong and produces a parse
1814 /// error, it still gets into the AST and the rest of the parser and
1815 /// type checker can run.
1816 #[derive(Clone, Copy)]
1817 pub(crate) struct FnParseMode {
1818 /// A function pointer that decides if, per-parameter `p`, `p` must have a
1819 /// pattern or just a type. This field affects parsing of the parameters list.
1822 /// fn foo(alef: A) -> X { X::new() }
1823 /// -----^^ affects parsing this part of the function signature
1825 /// if req_name returns false, then this name is optional
1830 /// if req_name returns true, this is an error
1833 /// Calling this function pointer should only return false if:
1835 /// * The item is being parsed inside of a trait definition.
1836 /// Within an impl block or a module, it should always evaluate
1838 /// * The span is from Edition 2015. In particular, you can get a
1839 /// 2015 span inside a 2021 crate using macros.
1840 pub req_name: ReqName,
1841 /// If this flag is set to `true`, then plain, semicolon-terminated function
1842 /// prototypes are not allowed here.
1845 /// fn foo(alef: A) -> X { X::new() }
1848 /// this is always allowed
1850 /// fn bar(alef: A, bet: B) -> X;
1853 /// if req_body is set to true, this is an error
1856 /// This field should only be set to false if the item is inside of a trait
1857 /// definition or extern block. Within an impl block or a module, it should
1858 /// always be set to true.
1862 /// Parsing of functions and methods.
1863 impl<'a> Parser<'a> {
1864 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1867 attrs: &mut Vec<Attribute>,
1868 fn_parse_mode: FnParseMode,
1871 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1872 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
1873 let ident = self.parse_ident()?; // `foo`
1874 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1876 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1877 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1879 let mut sig_hi = self.prev_token.span;
1880 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
1881 let fn_sig_span = sig_lo.to(sig_hi);
1882 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1885 /// Parse the "body" of a function.
1886 /// This can either be `;` when there's no body,
1887 /// or e.g. a block when the function is a provided one.
1890 attrs: &mut Vec<Attribute>,
1894 ) -> PResult<'a, Option<P<Block>>> {
1895 let has_semi = if req_body {
1896 self.token.kind == TokenKind::Semi
1898 // Only include `;` in list of expected tokens if body is not required
1899 self.check(&TokenKind::Semi)
1901 let (inner_attrs, body) = if has_semi {
1902 // Include the trailing semicolon in the span of the signature
1903 self.expect_semi()?;
1904 *sig_hi = self.prev_token.span;
1906 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1907 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1908 } else if self.token.kind == token::Eq {
1909 // Recover `fn foo() = $expr;`.
1911 let eq_sp = self.prev_token.span;
1912 let _ = self.parse_expr()?;
1913 self.expect_semi()?; // `;`
1914 let span = eq_sp.to(self.prev_token.span);
1915 self.struct_span_err(span, "function body cannot be `= expression;`")
1916 .multipart_suggestion(
1917 "surround the expression with `{` and `}` instead of `=` and `;`",
1918 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1919 Applicability::MachineApplicable,
1922 (Vec::new(), Some(self.mk_block_err(span)))
1924 let expected = if req_body {
1925 &[token::OpenDelim(token::Brace)][..]
1927 &[token::Semi, token::OpenDelim(token::Brace)]
1929 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
1930 if self.token.kind == token::CloseDelim(token::Brace) {
1931 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1932 // the AST for typechecking.
1933 err.span_label(ident.span, "while parsing this `fn`");
1941 attrs.extend(inner_attrs);
1945 /// Is the current token the start of an `FnHeader` / not a valid parse?
1947 /// `check_pub` adds additional `pub` to the checks in case users place it
1948 /// wrongly, can be used to ensure `pub` never comes after `default`.
1949 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
1950 // We use an over-approximation here.
1951 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1952 // `pub` is added in case users got confused with the ordering like `async pub fn`,
1953 // only if it wasn't preceeded by `default` as `default pub` is invalid.
1954 let quals: &[Symbol] = if check_pub {
1955 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1957 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1959 self.check_keyword(kw::Fn) // Definitely an `fn`.
1960 // `$qual fn` or `$qual $qual`:
1961 || quals.iter().any(|&kw| self.check_keyword(kw))
1962 && self.look_ahead(1, |t| {
1963 // `$qual fn`, e.g. `const fn` or `async fn`.
1964 t.is_keyword(kw::Fn)
1965 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1966 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
1967 // Rule out 2015 `const async: T = val`.
1969 // Rule out unsafe extern block.
1970 && !self.is_unsafe_foreign_mod())
1973 || self.check_keyword(kw::Extern)
1974 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1975 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1978 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1979 /// up to and including the `fn` keyword. The formal grammar is:
1982 /// Extern = "extern" StringLit? ;
1983 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1984 /// FnFrontMatter = FnQual "fn" ;
1987 /// `vis` represents the visibility that was already parsed, if any. Use
1988 /// `Visibility::Inherited` when no visibility is known.
1989 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
1990 let sp_start = self.token.span;
1991 let constness = self.parse_constness();
1993 let async_start_sp = self.token.span;
1994 let asyncness = self.parse_asyncness();
1996 let unsafe_start_sp = self.token.span;
1997 let unsafety = self.parse_unsafety();
1999 let ext_start_sp = self.token.span;
2000 let ext = self.parse_extern();
2002 if let Async::Yes { span, .. } = asyncness {
2003 self.ban_async_in_2015(span);
2006 if !self.eat_keyword(kw::Fn) {
2007 // It is possible for `expect_one_of` to recover given the contents of
2008 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2009 // account for this.
2010 match self.expect_one_of(&[], &[]) {
2012 Ok(false) => unreachable!(),
2014 // Qualifier keywords ordering check
2020 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2021 // that the keyword is already present and the second instance should be removed.
2022 let wrong_kw = if self.check_keyword(kw::Const) {
2024 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2025 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2027 } else if self.check_keyword(kw::Async) {
2029 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2030 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2032 } else if self.check_keyword(kw::Unsafe) {
2034 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2035 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2041 // The keyword is already present, suggest removal of the second instance
2042 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2043 let original_kw = self
2044 .span_to_snippet(original_sp)
2045 .expect("Span extracted directly from keyword should always work");
2047 err.span_suggestion(
2048 self.token.uninterpolated_span(),
2049 &format!("`{}` already used earlier, remove this one", original_kw),
2051 Applicability::MachineApplicable,
2053 .span_note(original_sp, &format!("`{}` first seen here", original_kw));
2055 // The keyword has not been seen yet, suggest correct placement in the function front matter
2056 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2057 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2058 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2059 let misplaced_qual_sp = self.token.uninterpolated_span();
2060 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2062 err.span_suggestion(
2063 correct_pos_sp.to(misplaced_qual_sp),
2064 &format!("`{}` must come before `{}`", misplaced_qual, current_qual),
2065 format!("{} {}", misplaced_qual, current_qual),
2066 Applicability::MachineApplicable,
2067 ).note("keyword order for functions declaration is `default`, `pub`, `const`, `async`, `unsafe`, `extern`");
2070 // Recover incorrect visibility order such as `async pub`
2071 else if self.check_keyword(kw::Pub) {
2072 let sp = sp_start.to(self.prev_token.span);
2073 if let Ok(snippet) = self.span_to_snippet(sp) {
2074 let current_vis = match self.parse_visibility(FollowedByType::No) {
2081 let vs = pprust::vis_to_string(¤t_vis);
2082 let vs = vs.trim_end();
2084 // There was no explicit visibility
2085 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2086 err.span_suggestion(
2087 sp_start.to(self.prev_token.span),
2088 &format!("visibility `{}` must come before `{}`", vs, snippet),
2089 format!("{} {}", vs, snippet),
2090 Applicability::MachineApplicable,
2093 // There was an explicit visibility
2095 err.span_suggestion(
2097 "there is already a visibility modifier, remove one",
2099 Applicability::MachineApplicable,
2101 .span_note(orig_vis.span, "explicit visibility first seen here");
2110 Ok(FnHeader { constness, unsafety, asyncness, ext })
2113 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2114 fn ban_async_in_2015(&self, span: Span) {
2115 if span.rust_2015() {
2116 let diag = self.diagnostic();
2117 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2118 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2119 .help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION))
2120 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
2125 /// Parses the parameter list and result type of a function declaration.
2126 pub(super) fn parse_fn_decl(
2129 ret_allow_plus: AllowPlus,
2130 recover_return_sign: RecoverReturnSign,
2131 ) -> PResult<'a, P<FnDecl>> {
2133 inputs: self.parse_fn_params(req_name)?,
2134 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2138 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2139 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2140 let mut first_param = true;
2141 // Parse the arguments, starting out with `self` being allowed...
2142 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2143 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2145 let lo = p.prev_token.span;
2146 // Skip every token until next possible arg or end.
2147 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
2148 // Create a placeholder argument for proper arg count (issue #34264).
2149 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2151 // ...now that we've parsed the first argument, `self` is no longer allowed.
2152 first_param = false;
2155 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2156 self.deduplicate_recovered_params_names(&mut params);
2160 /// Parses a single function parameter.
2162 /// - `self` is syntactically allowed when `first_param` holds.
2163 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2164 let lo = self.token.span;
2165 let attrs = self.parse_outer_attributes()?;
2166 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2167 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2168 if let Some(mut param) = this.parse_self_param()? {
2169 param.attrs = attrs.into();
2170 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2171 return Ok((res?, TrailingToken::None));
2174 let is_name_required = match this.token.kind {
2175 token::DotDotDot => false,
2176 _ => req_name(this.token.span.edition()),
2178 let (pat, ty) = if is_name_required || this.is_named_param() {
2179 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2181 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2183 let mut err = this.unexpected::<()>().unwrap_err();
2184 return if let Some(ident) =
2185 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2188 Ok((dummy_arg(ident), TrailingToken::None))
2194 this.eat_incorrect_doc_comment_for_param_type();
2195 (pat, this.parse_ty_for_param()?)
2197 debug!("parse_param_general ident_to_pat");
2198 let parser_snapshot_before_ty = this.clone();
2199 this.eat_incorrect_doc_comment_for_param_type();
2200 let mut ty = this.parse_ty_for_param();
2202 && this.token != token::Comma
2203 && this.token != token::CloseDelim(token::Paren)
2205 // This wasn't actually a type, but a pattern looking like a type,
2206 // so we are going to rollback and re-parse for recovery.
2207 ty = this.unexpected();
2211 let ident = Ident::new(kw::Empty, this.prev_token.span);
2212 let bm = BindingMode::ByValue(Mutability::Not);
2213 let pat = this.mk_pat_ident(ty.span, bm, ident);
2216 // If this is a C-variadic argument and we hit an error, return the error.
2217 Err(err) if this.token == token::DotDotDot => return Err(err),
2218 // Recover from attempting to parse the argument as a type without pattern.
2221 *this = parser_snapshot_before_ty;
2222 this.recover_arg_parse()?
2227 let span = lo.until(this.token.span);
2231 attrs: attrs.into(),
2232 id: ast::DUMMY_NODE_ID,
2233 is_placeholder: false,
2238 TrailingToken::None,
2243 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2244 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2245 // Extract an identifier *after* having confirmed that the token is one.
2246 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2247 Some((ident, false)) => {
2251 _ => unreachable!(),
2253 // Is `self` `n` tokens ahead?
2254 let is_isolated_self = |this: &Self, n| {
2255 this.is_keyword_ahead(n, &[kw::SelfLower])
2256 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2258 // Is `mut self` `n` tokens ahead?
2259 let is_isolated_mut_self =
2260 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2261 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2262 let parse_self_possibly_typed = |this: &mut Self, m| {
2263 let eself_ident = expect_self_ident(this);
2264 let eself_hi = this.prev_token.span;
2265 let eself = if this.eat(&token::Colon) {
2266 SelfKind::Explicit(this.parse_ty()?, m)
2270 Ok((eself, eself_ident, eself_hi))
2272 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2273 let recover_self_ptr = |this: &mut Self| {
2274 let msg = "cannot pass `self` by raw pointer";
2275 let span = this.token.span;
2276 this.struct_span_err(span, msg).span_label(span, msg).emit();
2278 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2281 // Parse optional `self` parameter of a method.
2282 // Only a limited set of initial token sequences is considered `self` parameters; anything
2283 // else is parsed as a normal function parameter list, so some lookahead is required.
2284 let eself_lo = self.token.span;
2285 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2286 token::BinOp(token::And) => {
2287 let eself = if is_isolated_self(self, 1) {
2290 SelfKind::Region(None, Mutability::Not)
2291 } else if is_isolated_mut_self(self, 1) {
2295 SelfKind::Region(None, Mutability::Mut)
2296 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2299 let lt = self.expect_lifetime();
2300 SelfKind::Region(Some(lt), Mutability::Not)
2301 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2304 let lt = self.expect_lifetime();
2306 SelfKind::Region(Some(lt), Mutability::Mut)
2311 (eself, expect_self_ident(self), self.prev_token.span)
2314 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2316 recover_self_ptr(self)?
2318 // `*mut self` and `*const self`
2319 token::BinOp(token::Star)
2320 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2324 recover_self_ptr(self)?
2326 // `self` and `self: TYPE`
2327 token::Ident(..) if is_isolated_self(self, 0) => {
2328 parse_self_possibly_typed(self, Mutability::Not)?
2330 // `mut self` and `mut self: TYPE`
2331 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2333 parse_self_possibly_typed(self, Mutability::Mut)?
2335 _ => return Ok(None),
2338 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2339 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2342 fn is_named_param(&self) -> bool {
2343 let offset = match self.token.kind {
2344 token::Interpolated(ref nt) => match **nt {
2345 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2348 token::BinOp(token::And) | token::AndAnd => 1,
2349 _ if self.token.is_keyword(kw::Mut) => 1,
2353 self.look_ahead(offset, |t| t.is_ident())
2354 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2357 fn recover_first_param(&mut self) -> &'static str {
2359 .parse_outer_attributes()
2360 .and_then(|_| self.parse_self_param())
2361 .map_err(|e| e.cancel())
2363 Ok(Some(_)) => "method",
2369 enum IsMacroRulesItem {
2370 Yes { has_bang: bool },