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 end.meta_kind().is_some() {
453 if self.token.kind == TokenKind::Semi {
454 err.span_suggestion_verbose(
456 "consider removing this semicolon",
458 Applicability::MaybeIncorrect,
462 if let [.., penultimate, _] = attrs {
463 err.span_label(start.span.to(penultimate.span), "other attributes here");
468 fn is_async_fn(&self) -> bool {
469 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
472 fn parse_polarity(&mut self) -> ast::ImplPolarity {
473 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
474 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
476 ast::ImplPolarity::Negative(self.prev_token.span)
478 ast::ImplPolarity::Positive
482 /// Parses an implementation item.
485 /// impl<'a, T> TYPE { /* impl items */ }
486 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
487 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
488 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
491 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
493 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
494 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
498 attrs: &mut Vec<Attribute>,
499 defaultness: Defaultness,
500 ) -> PResult<'a, ItemInfo> {
501 let unsafety = self.parse_unsafety();
502 self.expect_keyword(kw::Impl)?;
504 // First, parse generic parameters if necessary.
505 let mut generics = if self.choose_generics_over_qpath(0) {
506 self.parse_generics()?
508 let mut generics = Generics::default();
510 // /\ this is where `generics.span` should point when there are no type params.
511 generics.span = self.prev_token.span.shrink_to_hi();
515 let constness = self.parse_constness();
516 if let Const::Yes(span) = constness {
517 self.sess.gated_spans.gate(sym::const_trait_impl, span);
520 let polarity = self.parse_polarity();
522 // Parse both types and traits as a type, then reinterpret if necessary.
523 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
524 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
526 let span = self.prev_token.span.between(self.token.span);
527 self.struct_span_err(span, "missing trait in a trait impl")
532 Applicability::HasPlaceholders,
535 span.to(self.token.span),
536 "for an inherent impl, drop this `for`",
538 Applicability::MaybeIncorrect,
542 kind: TyKind::Path(None, err_path(span)),
548 self.parse_ty_with_generics_recovery(&generics)?
551 // If `for` is missing we try to recover.
552 let has_for = self.eat_keyword(kw::For);
553 let missing_for_span = self.prev_token.span.between(self.token.span);
555 let ty_second = if self.token == token::DotDot {
556 // We need to report this error after `cfg` expansion for compatibility reasons
557 self.bump(); // `..`, do not add it to expected tokens
558 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
559 } else if has_for || self.token.can_begin_type() {
560 Some(self.parse_ty()?)
565 generics.where_clause = self.parse_where_clause()?;
567 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
569 let item_kind = match ty_second {
571 // impl Trait for Type
573 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
574 .span_suggestion_short(
578 Applicability::MachineApplicable,
583 let ty_first = ty_first.into_inner();
584 let path = match ty_first.kind {
585 // This notably includes paths passed through `ty` macro fragments (#46438).
586 TyKind::Path(None, path) => path,
588 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
589 err_path(ty_first.span)
592 let trait_ref = TraitRef { path, ref_id: ty_first.id };
594 ItemKind::Impl(Box::new(Impl {
600 of_trait: Some(trait_ref),
607 ItemKind::Impl(Box::new(Impl {
620 Ok((Ident::empty(), item_kind))
623 fn parse_item_list<T>(
625 attrs: &mut Vec<Attribute>,
626 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
627 ) -> PResult<'a, Vec<T>> {
628 let open_brace_span = self.token.span;
629 self.expect(&token::OpenDelim(token::Brace))?;
630 attrs.append(&mut self.parse_inner_attributes()?);
632 let mut items = Vec::new();
633 while !self.eat(&token::CloseDelim(token::Brace)) {
634 if self.recover_doc_comment_before_brace() {
637 match parse_item(self) {
639 // We have to bail or we'll potentially never make progress.
640 let non_item_span = self.token.span;
641 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
642 self.struct_span_err(non_item_span, "non-item in item list")
643 .span_label(open_brace_span, "item list starts here")
644 .span_label(non_item_span, "non-item starts here")
645 .span_label(self.prev_token.span, "item list ends here")
649 Ok(Some(item)) => items.extend(item),
651 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
652 err.span_label(open_brace_span, "while parsing this item list starting here")
653 .span_label(self.prev_token.span, "the item list ends here")
662 /// Recover on a doc comment before `}`.
663 fn recover_doc_comment_before_brace(&mut self) -> bool {
664 if let token::DocComment(..) = self.token.kind {
665 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
670 "found a documentation comment that doesn't document anything",
672 .span_label(self.token.span, "this doc comment doesn't document anything")
674 "doc comments must come before what they document, maybe a \
675 comment was intended with `//`?",
685 /// Parses defaultness (i.e., `default` or nothing).
686 fn parse_defaultness(&mut self) -> Defaultness {
687 // We are interested in `default` followed by another identifier.
688 // However, we must avoid keywords that occur as binary operators.
689 // Currently, the only applicable keyword is `as` (`default as Ty`).
690 if self.check_keyword(kw::Default)
691 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
693 self.bump(); // `default`
694 Defaultness::Default(self.prev_token.uninterpolated_span())
700 /// Is this an `(unsafe auto? | auto) trait` item?
701 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
703 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
705 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
708 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
709 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
710 let unsafety = self.parse_unsafety();
711 // Parse optional `auto` prefix.
712 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
714 self.expect_keyword(kw::Trait)?;
715 let ident = self.parse_ident()?;
716 let mut generics = self.parse_generics()?;
718 // Parse optional colon and supertrait bounds.
719 let had_colon = self.eat(&token::Colon);
720 let span_at_colon = self.prev_token.span;
721 let bounds = if had_colon {
722 self.parse_generic_bounds(Some(self.prev_token.span))?
727 let span_before_eq = self.prev_token.span;
728 if self.eat(&token::Eq) {
729 // It's a trait alias.
731 let span = span_at_colon.to(span_before_eq);
732 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
735 let bounds = self.parse_generic_bounds(None)?;
736 generics.where_clause = self.parse_where_clause()?;
739 let whole_span = lo.to(self.prev_token.span);
740 if is_auto == IsAuto::Yes {
741 let msg = "trait aliases cannot be `auto`";
742 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
744 if let Unsafe::Yes(_) = unsafety {
745 let msg = "trait aliases cannot be `unsafe`";
746 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
749 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
751 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
753 // It's a normal trait.
754 generics.where_clause = self.parse_where_clause()?;
755 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
758 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
763 pub fn parse_impl_item(
765 force_collect: ForceCollect,
766 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
767 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
768 self.parse_assoc_item(fn_parse_mode, force_collect)
771 pub fn parse_trait_item(
773 force_collect: ForceCollect,
774 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
776 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
777 self.parse_assoc_item(fn_parse_mode, force_collect)
780 /// Parses associated items.
783 fn_parse_mode: FnParseMode,
784 force_collect: ForceCollect,
785 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
786 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
787 |Item { attrs, id, span, vis, ident, kind, tokens }| {
788 let kind = match AssocItemKind::try_from(kind) {
790 Err(kind) => match kind {
791 ItemKind::Static(a, _, b) => {
792 self.struct_span_err(span, "associated `static` items are not allowed")
794 AssocItemKind::Const(Defaultness::Final, a, b)
796 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
799 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
804 /// Emits an error that the where clause at the end of a type alias is not
805 /// allowed and suggests moving it.
806 fn error_ty_alias_where(
808 before_where_clause_present: bool,
809 before_where_clause_span: Span,
810 after_predicates: &[WherePredicate],
811 after_where_clause_span: Span,
812 ) -> ErrorGuaranteed {
814 self.struct_span_err(after_where_clause_span, "where clause not allowed here");
815 if !after_predicates.is_empty() {
816 let mut state = crate::pprust::State::new();
817 if !before_where_clause_present {
819 state.word_space("where");
821 state.word_space(",");
823 let mut first = true;
824 for p in after_predicates.iter() {
826 state.word_space(",");
829 state.print_where_predicate(p);
831 let suggestion = state.s.eof();
833 before_where_clause_span.shrink_to_hi(),
836 Applicability::MachineApplicable,
842 /// Parses a `type` alias with the following grammar:
844 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
846 /// The `"type"` has already been eaten.
847 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
848 let ident = self.parse_ident()?;
849 let mut generics = self.parse_generics()?;
851 // Parse optional colon and param bounds.
853 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
855 generics.where_clause = self.parse_where_clause()?;
857 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
859 if self.token.is_keyword(kw::Where) {
860 let after_where_clause = self.parse_where_clause()?;
862 self.error_ty_alias_where(
863 generics.where_clause.has_where_token,
864 generics.where_clause.span,
865 &after_where_clause.predicates,
866 after_where_clause.span,
869 generics.where_clause.predicates.extend(after_where_clause.predicates.into_iter());
874 Ok((ident, ItemKind::TyAlias(Box::new(TyAlias { defaultness, generics, bounds, ty }))))
877 /// Parses a `UseTree`.
880 /// USE_TREE = [`::`] `*` |
881 /// [`::`] `{` USE_TREE_LIST `}` |
883 /// PATH `::` `{` USE_TREE_LIST `}` |
884 /// PATH [`as` IDENT]
886 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
887 let lo = self.token.span;
889 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
890 let kind = if self.check(&token::OpenDelim(token::Brace))
891 || self.check(&token::BinOp(token::Star))
892 || self.is_import_coupler()
894 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
895 let mod_sep_ctxt = self.token.span.ctxt();
896 if self.eat(&token::ModSep) {
899 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
902 self.parse_use_tree_glob_or_nested()?
904 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
905 prefix = self.parse_path(PathStyle::Mod)?;
907 if self.eat(&token::ModSep) {
908 self.parse_use_tree_glob_or_nested()?
910 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
914 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
917 /// Parses `*` or `{...}`.
918 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
919 Ok(if self.eat(&token::BinOp(token::Star)) {
922 UseTreeKind::Nested(self.parse_use_tree_list()?)
926 /// Parses a `UseTreeKind::Nested(list)`.
929 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
931 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
932 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
936 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
937 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
940 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
941 match self.token.ident() {
942 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
946 _ => self.parse_ident(),
950 /// Parses `extern crate` links.
955 /// extern crate foo;
956 /// extern crate bar as foo;
958 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
959 // Accept `extern crate name-like-this` for better diagnostics
960 let orig_name = self.parse_crate_name_with_dashes()?;
961 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
962 (rename, Some(orig_name.name))
967 Ok((item_name, ItemKind::ExternCrate(orig_name)))
970 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
971 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
972 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
974 let mut ident = if self.token.is_keyword(kw::SelfLower) {
975 self.parse_path_segment_ident()
979 let mut idents = vec![];
980 let mut replacement = vec![];
981 let mut fixed_crate_name = false;
982 // Accept `extern crate name-like-this` for better diagnostics.
983 let dash = token::BinOp(token::BinOpToken::Minus);
984 if self.token == dash {
985 // Do not include `-` as part of the expected tokens list.
986 while self.eat(&dash) {
987 fixed_crate_name = true;
988 replacement.push((self.prev_token.span, "_".to_string()));
989 idents.push(self.parse_ident()?);
992 if fixed_crate_name {
993 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
994 let mut fixed_name = format!("{}", ident.name);
996 fixed_name.push_str(&format!("_{}", part.name));
998 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1000 self.struct_span_err(fixed_name_sp, error_msg)
1001 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1002 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1008 /// Parses `extern` for foreign ABIs modules.
1010 /// `extern` is expected to have been consumed before calling this method.
1014 /// ```ignore (only-for-syntax-highlight)
1018 fn parse_item_foreign_mod(
1020 attrs: &mut Vec<Attribute>,
1022 ) -> PResult<'a, ItemInfo> {
1023 let abi = self.parse_abi(); // ABI?
1024 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?;
1025 let module = ast::ForeignMod { unsafety, abi, items };
1026 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1029 /// Parses a foreign item (one in an `extern { ... }` block).
1030 pub fn parse_foreign_item(
1032 force_collect: ForceCollect,
1033 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1034 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1035 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1036 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1037 let kind = match ForeignItemKind::try_from(kind) {
1039 Err(kind) => match kind {
1040 ItemKind::Const(_, a, b) => {
1041 self.error_on_foreign_const(span, ident);
1042 ForeignItemKind::Static(a, Mutability::Not, b)
1044 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1047 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1052 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1053 let span = self.sess.source_map().guess_head_span(span);
1054 let descr = kind.descr();
1055 self.struct_span_err(span, &format!("{} is not supported in {}", descr, ctx))
1056 .help(&format!("consider moving the {} out to a nearby module scope", descr))
1061 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1062 self.struct_span_err(ident.span, "extern items cannot be `const`")
1064 span.with_hi(ident.span.lo()),
1065 "try using a static value",
1066 "static ".to_string(),
1067 Applicability::MachineApplicable,
1069 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1073 fn is_unsafe_foreign_mod(&self) -> bool {
1074 self.token.is_keyword(kw::Unsafe)
1075 && self.is_keyword_ahead(1, &[kw::Extern])
1077 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1078 |t| t.kind == token::OpenDelim(token::Brace),
1082 fn is_static_global(&mut self) -> bool {
1083 if self.check_keyword(kw::Static) {
1084 // Check if this could be a closure.
1085 !self.look_ahead(1, |token| {
1086 if token.is_keyword(kw::Move) {
1089 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1096 /// Recover on `const mut` with `const` already eaten.
1097 fn recover_const_mut(&mut self, const_span: Span) {
1098 if self.eat_keyword(kw::Mut) {
1099 let span = self.prev_token.span;
1100 self.struct_span_err(span, "const globals cannot be mutable")
1101 .span_label(span, "cannot be mutable")
1104 "you might want to declare a static instead",
1105 "static".to_owned(),
1106 Applicability::MaybeIncorrect,
1112 /// Recover on `const impl` with `const` already eaten.
1113 fn recover_const_impl(
1116 attrs: &mut Vec<Attribute>,
1117 defaultness: Defaultness,
1118 ) -> PResult<'a, ItemInfo> {
1119 let impl_span = self.token.span;
1120 let mut err = self.expected_ident_found();
1122 // Only try to recover if this is implementing a trait for a type
1123 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1124 Ok(impl_info) => impl_info,
1125 Err(recovery_error) => {
1126 // Recovery failed, raise the "expected identifier" error
1127 recovery_error.cancel();
1133 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1134 *constness = Const::Yes(const_span);
1136 let before_trait = trai.path.span.shrink_to_lo();
1137 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1138 err.multipart_suggestion(
1139 "you might have meant to write a const trait impl",
1140 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1141 Applicability::MaybeIncorrect,
1145 ItemKind::Impl { .. } => return Err(err),
1146 _ => unreachable!(),
1152 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1153 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1155 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1156 fn parse_item_global(
1158 m: Option<Mutability>,
1159 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1160 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1162 // Parse the type of a `const` or `static mut?` item.
1163 // That is, the `":" $ty` fragment.
1164 let ty = if self.eat(&token::Colon) {
1167 self.recover_missing_const_type(id, m)
1170 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1171 self.expect_semi()?;
1175 /// We were supposed to parse `:` but the `:` was missing.
1176 /// This means that the type is missing.
1177 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1178 // Construct the error and stash it away with the hope
1179 // that typeck will later enrich the error with a type.
1180 let kind = match m {
1181 Some(Mutability::Mut) => "static mut",
1182 Some(Mutability::Not) => "static",
1185 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1186 err.span_suggestion(
1188 "provide a type for the item",
1189 format!("{}: <type>", id),
1190 Applicability::HasPlaceholders,
1192 err.stash(id.span, StashKey::ItemNoType);
1194 // The user intended that the type be inferred,
1195 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1196 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None })
1199 /// Parses an enum declaration.
1200 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1201 let id = self.parse_ident()?;
1202 let mut generics = self.parse_generics()?;
1203 generics.where_clause = self.parse_where_clause()?;
1206 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1207 self.recover_stmt();
1211 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1212 Ok((id, ItemKind::Enum(enum_definition, generics)))
1215 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1216 let variant_attrs = self.parse_outer_attributes()?;
1217 self.collect_tokens_trailing_token(
1220 |this, variant_attrs| {
1221 let vlo = this.token.span;
1223 let vis = this.parse_visibility(FollowedByType::No)?;
1224 if !this.recover_nested_adt_item(kw::Enum)? {
1225 return Ok((None, TrailingToken::None));
1227 let ident = this.parse_field_ident("enum", vlo)?;
1229 let struct_def = if this.check(&token::OpenDelim(token::Brace)) {
1230 // Parse a struct variant.
1231 let (fields, recovered) = this.parse_record_struct_body("struct", false)?;
1232 VariantData::Struct(fields, recovered)
1233 } else if this.check(&token::OpenDelim(token::Paren)) {
1234 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1236 VariantData::Unit(DUMMY_NODE_ID)
1240 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1242 let vr = ast::Variant {
1246 attrs: variant_attrs.into(),
1249 span: vlo.to(this.prev_token.span),
1250 is_placeholder: false,
1253 Ok((Some(vr), TrailingToken::MaybeComma))
1258 /// Parses `struct Foo { ... }`.
1259 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1260 let class_name = self.parse_ident()?;
1262 let mut generics = self.parse_generics()?;
1264 // There is a special case worth noting here, as reported in issue #17904.
1265 // If we are parsing a tuple struct it is the case that the where clause
1266 // should follow the field list. Like so:
1268 // struct Foo<T>(T) where T: Copy;
1270 // If we are parsing a normal record-style struct it is the case
1271 // that the where clause comes before the body, and after the generics.
1272 // So if we look ahead and see a brace or a where-clause we begin
1273 // parsing a record style struct.
1275 // Otherwise if we look ahead and see a paren we parse a tuple-style
1278 let vdata = if self.token.is_keyword(kw::Where) {
1279 generics.where_clause = self.parse_where_clause()?;
1280 if self.eat(&token::Semi) {
1281 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1282 VariantData::Unit(DUMMY_NODE_ID)
1284 // If we see: `struct Foo<T> where T: Copy { ... }`
1285 let (fields, recovered) =
1286 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1287 VariantData::Struct(fields, recovered)
1289 // No `where` so: `struct Foo<T>;`
1290 } else if self.eat(&token::Semi) {
1291 VariantData::Unit(DUMMY_NODE_ID)
1292 // Record-style struct definition
1293 } else if self.token == token::OpenDelim(token::Brace) {
1294 let (fields, recovered) =
1295 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1296 VariantData::Struct(fields, recovered)
1297 // Tuple-style struct definition with optional where-clause.
1298 } else if self.token == token::OpenDelim(token::Paren) {
1299 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1300 generics.where_clause = self.parse_where_clause()?;
1301 self.expect_semi()?;
1304 let token_str = super::token_descr(&self.token);
1306 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1309 let mut err = self.struct_span_err(self.token.span, msg);
1310 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1314 Ok((class_name, ItemKind::Struct(vdata, generics)))
1317 /// Parses `union Foo { ... }`.
1318 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1319 let class_name = self.parse_ident()?;
1321 let mut generics = self.parse_generics()?;
1323 let vdata = if self.token.is_keyword(kw::Where) {
1324 generics.where_clause = self.parse_where_clause()?;
1325 let (fields, recovered) =
1326 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1327 VariantData::Struct(fields, recovered)
1328 } else if self.token == token::OpenDelim(token::Brace) {
1329 let (fields, recovered) =
1330 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1331 VariantData::Struct(fields, recovered)
1333 let token_str = super::token_descr(&self.token);
1334 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1335 let mut err = self.struct_span_err(self.token.span, msg);
1336 err.span_label(self.token.span, "expected `where` or `{` after union name");
1340 Ok((class_name, ItemKind::Union(vdata, generics)))
1343 fn parse_record_struct_body(
1347 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1348 let mut fields = Vec::new();
1349 let mut recovered = false;
1350 if self.eat(&token::OpenDelim(token::Brace)) {
1351 while self.token != token::CloseDelim(token::Brace) {
1352 let field = self.parse_field_def(adt_ty).map_err(|e| {
1353 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1358 Ok(field) => fields.push(field),
1365 self.eat(&token::CloseDelim(token::Brace));
1367 let token_str = super::token_descr(&self.token);
1369 "expected {}`{{` after struct name, found {}",
1370 if parsed_where { "" } else { "`where`, or " },
1373 let mut err = self.struct_span_err(self.token.span, msg);
1377 "expected {}`{{` after struct name",
1378 if parsed_where { "" } else { "`where`, or " }
1384 Ok((fields, recovered))
1387 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1388 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1389 // Unit like structs are handled in parse_item_struct function
1390 self.parse_paren_comma_seq(|p| {
1391 let attrs = p.parse_outer_attributes()?;
1392 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1393 let lo = p.token.span;
1394 let vis = p.parse_visibility(FollowedByType::Yes)?;
1395 let ty = p.parse_ty()?;
1399 span: lo.to(ty.span),
1404 attrs: attrs.into(),
1405 is_placeholder: false,
1407 TrailingToken::MaybeComma,
1414 /// Parses an element of a struct declaration.
1415 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1416 let attrs = self.parse_outer_attributes()?;
1417 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1418 let lo = this.token.span;
1419 let vis = this.parse_visibility(FollowedByType::No)?;
1420 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1424 /// Parses a structure field declaration.
1425 fn parse_single_struct_field(
1430 attrs: Vec<Attribute>,
1431 ) -> PResult<'a, FieldDef> {
1432 let mut seen_comma: bool = false;
1433 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1434 if self.token == token::Comma {
1437 match self.token.kind {
1441 token::CloseDelim(token::Brace) => {}
1442 token::DocComment(..) => {
1443 let previous_span = self.prev_token.span;
1444 let mut err = self.span_err(self.token.span, Error::UselessDocComment);
1445 self.bump(); // consume the doc comment
1446 let comma_after_doc_seen = self.eat(&token::Comma);
1447 // `seen_comma` is always false, because we are inside doc block
1448 // condition is here to make code more readable
1449 if !seen_comma && comma_after_doc_seen {
1452 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1456 let sp = self.sess.source_map().next_point(previous_span);
1457 err.span_suggestion(
1459 "missing comma here",
1461 Applicability::MachineApplicable,
1468 let sp = self.prev_token.span.shrink_to_hi();
1469 let mut err = self.struct_span_err(
1471 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1474 // Try to recover extra trailing angle brackets
1475 let mut recovered = false;
1476 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1477 if let Some(last_segment) = segments.last() {
1478 recovered = self.check_trailing_angle_brackets(
1480 &[&token::Comma, &token::CloseDelim(token::Brace)],
1483 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1485 self.eat(&token::Comma);
1486 // `check_trailing_angle_brackets` already emitted a nicer error
1487 // NOTE(eddyb) this was `.cancel()`, but `err`
1488 // gets returned, so we can't fully defuse it.
1489 err.downgrade_to_delayed_bug();
1494 if self.token.is_ident() {
1495 // This is likely another field; emit the diagnostic and keep going
1496 err.span_suggestion(
1498 "try adding a comma",
1500 Applicability::MachineApplicable,
1507 // Make sure an error was emitted (either by recovering an angle bracket,
1508 // or by finding an identifier as the next token), since we're
1509 // going to continue parsing
1510 assert!(self.sess.span_diagnostic.has_errors());
1519 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1520 if let Err(mut err) = self.expect(&token::Colon) {
1521 let sm = self.sess.source_map();
1522 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1523 let semi_typo = self.token.kind == token::Semi
1524 && self.look_ahead(1, |t| {
1526 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1527 // when there's no type and `;` was used instead of a comma.
1528 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1529 (Ok(l), Ok(r)) => l.line == r.line,
1533 if eq_typo || semi_typo {
1535 // Gracefully handle small typos.
1536 err.span_suggestion_short(
1537 self.prev_token.span,
1538 "field names and their types are separated with `:`",
1540 Applicability::MachineApplicable,
1550 /// Parses a structure field.
1551 fn parse_name_and_ty(
1556 attrs: Vec<Attribute>,
1557 ) -> PResult<'a, FieldDef> {
1558 let name = self.parse_field_ident(adt_ty, lo)?;
1559 self.expect_field_ty_separator()?;
1560 let ty = self.parse_ty()?;
1561 if self.token.kind == token::Eq {
1563 let const_expr = self.parse_anon_const_expr()?;
1564 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1565 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1568 "remove this unsupported default value",
1570 Applicability::MachineApplicable,
1575 span: lo.to(self.prev_token.span),
1580 attrs: attrs.into(),
1581 is_placeholder: false,
1585 /// Parses a field identifier. Specialized version of `parse_ident_common`
1586 /// for better diagnostics and suggestions.
1587 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1588 let (ident, is_raw) = self.ident_or_err()?;
1589 if !is_raw && ident.is_reserved() {
1590 let err = if self.check_fn_front_matter(false) {
1591 let inherited_vis = Visibility {
1592 span: rustc_span::DUMMY_SP,
1593 kind: VisibilityKind::Inherited,
1596 // We use `parse_fn` to get a span for the function
1597 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1598 if let Err(mut db) =
1599 self.parse_fn(&mut Vec::new(), fn_parse_mode, lo, &inherited_vis)
1603 let mut err = self.struct_span_err(
1604 lo.to(self.prev_token.span),
1605 &format!("functions are not allowed in {} definitions", adt_ty),
1607 err.help("unlike in C++, Java, and C#, functions are declared in `impl` blocks");
1608 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1611 self.expected_ident_found()
1619 /// Parses a declarative macro 2.0 definition.
1620 /// The `macro` keyword has already been parsed.
1622 /// MacBody = "{" TOKEN_STREAM "}" ;
1623 /// MacParams = "(" TOKEN_STREAM ")" ;
1624 /// DeclMac = "macro" Ident MacParams? MacBody ;
1626 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1627 let ident = self.parse_ident()?;
1628 let body = if self.check(&token::OpenDelim(token::Brace)) {
1629 self.parse_mac_args()? // `MacBody`
1630 } else if self.check(&token::OpenDelim(token::Paren)) {
1631 let params = self.parse_token_tree(); // `MacParams`
1632 let pspan = params.span();
1633 if !self.check(&token::OpenDelim(token::Brace)) {
1634 return self.unexpected();
1636 let body = self.parse_token_tree(); // `MacBody`
1637 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1638 let bspan = body.span();
1639 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1640 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1641 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1642 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1644 return self.unexpected();
1647 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1648 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1651 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1653 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1654 if self.check_keyword(kw::MacroRules) {
1655 let macro_rules_span = self.token.span;
1657 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1658 return IsMacroRulesItem::Yes { has_bang: true };
1659 } else if self.look_ahead(1, |t| (t.is_ident())) {
1661 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1665 "macro_rules!".to_owned(),
1666 Applicability::MachineApplicable,
1670 return IsMacroRulesItem::Yes { has_bang: false };
1674 IsMacroRulesItem::No
1677 /// Parses a `macro_rules! foo { ... }` declarative macro.
1678 fn parse_item_macro_rules(
1682 ) -> PResult<'a, ItemInfo> {
1683 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1686 self.expect(&token::Not)?; // `!`
1688 let ident = self.parse_ident()?;
1690 if self.eat(&token::Not) {
1691 // Handle macro_rules! foo!
1692 let span = self.prev_token.span;
1693 self.struct_span_err(span, "macro names aren't followed by a `!`")
1698 Applicability::MachineApplicable,
1703 let body = self.parse_mac_args()?;
1704 self.eat_semi_for_macro_if_needed(&body);
1705 self.complain_if_pub_macro(vis, true);
1707 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1710 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1711 /// If that's not the case, emit an error.
1712 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1713 if let VisibilityKind::Inherited = vis.kind {
1717 let vstr = pprust::vis_to_string(vis);
1718 let vstr = vstr.trim_end();
1720 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1721 self.struct_span_err(vis.span, &msg)
1724 "try exporting the macro",
1725 "#[macro_export]".to_owned(),
1726 Applicability::MaybeIncorrect, // speculative
1730 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1733 "remove the visibility",
1735 Applicability::MachineApplicable,
1737 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1742 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1743 if args.need_semicolon() && !self.eat(&token::Semi) {
1744 self.report_invalid_macro_expansion_item(args);
1748 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1749 let span = args.span().expect("undelimited macro call");
1750 let mut err = self.struct_span_err(
1752 "macros that expand to items must be delimited with braces or followed by a semicolon",
1754 if self.unclosed_delims.is_empty() {
1755 let DelimSpan { open, close } = match args {
1756 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1757 MacArgs::Delimited(dspan, ..) => *dspan,
1759 err.multipart_suggestion(
1760 "change the delimiters to curly braces",
1761 vec![(open, "{".to_string()), (close, '}'.to_string())],
1762 Applicability::MaybeIncorrect,
1765 err.span_suggestion(
1767 "change the delimiters to curly braces",
1768 " { /* items */ }".to_string(),
1769 Applicability::HasPlaceholders,
1772 err.span_suggestion(
1773 span.shrink_to_hi(),
1776 Applicability::MaybeIncorrect,
1781 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1782 /// it is, we try to parse the item and report error about nested types.
1783 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1784 if (self.token.is_keyword(kw::Enum)
1785 || self.token.is_keyword(kw::Struct)
1786 || self.token.is_keyword(kw::Union))
1787 && self.look_ahead(1, |t| t.is_ident())
1789 let kw_token = self.token.clone();
1790 let kw_str = pprust::token_to_string(&kw_token);
1791 let item = self.parse_item(ForceCollect::No)?;
1793 self.struct_span_err(
1795 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1799 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1801 Applicability::MaybeIncorrect,
1804 // We successfully parsed the item but we must inform the caller about nested problem.
1811 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1813 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1815 /// This function pointer accepts an edition, because in edition 2015, trait declarations
1816 /// were allowed to omit parameter names. In 2018, they became required.
1817 type ReqName = fn(Edition) -> bool;
1819 /// Parsing configuration for functions.
1821 /// The syntax of function items is slightly different within trait definitions,
1822 /// impl blocks, and modules. It is still parsed using the same code, just with
1823 /// different flags set, so that even when the input is wrong and produces a parse
1824 /// error, it still gets into the AST and the rest of the parser and
1825 /// type checker can run.
1826 #[derive(Clone, Copy)]
1827 pub(crate) struct FnParseMode {
1828 /// A function pointer that decides if, per-parameter `p`, `p` must have a
1829 /// pattern or just a type. This field affects parsing of the parameters list.
1832 /// fn foo(alef: A) -> X { X::new() }
1833 /// -----^^ affects parsing this part of the function signature
1835 /// if req_name returns false, then this name is optional
1840 /// if req_name returns true, this is an error
1843 /// Calling this function pointer should only return false if:
1845 /// * The item is being parsed inside of a trait definition.
1846 /// Within an impl block or a module, it should always evaluate
1848 /// * The span is from Edition 2015. In particular, you can get a
1849 /// 2015 span inside a 2021 crate using macros.
1850 pub req_name: ReqName,
1851 /// If this flag is set to `true`, then plain, semicolon-terminated function
1852 /// prototypes are not allowed here.
1855 /// fn foo(alef: A) -> X { X::new() }
1858 /// this is always allowed
1860 /// fn bar(alef: A, bet: B) -> X;
1863 /// if req_body is set to true, this is an error
1866 /// This field should only be set to false if the item is inside of a trait
1867 /// definition or extern block. Within an impl block or a module, it should
1868 /// always be set to true.
1872 /// Parsing of functions and methods.
1873 impl<'a> Parser<'a> {
1874 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1877 attrs: &mut Vec<Attribute>,
1878 fn_parse_mode: FnParseMode,
1881 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1882 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
1883 let ident = self.parse_ident()?; // `foo`
1884 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1886 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1887 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1889 let mut sig_hi = self.prev_token.span;
1890 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
1891 let fn_sig_span = sig_lo.to(sig_hi);
1892 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1895 /// Parse the "body" of a function.
1896 /// This can either be `;` when there's no body,
1897 /// or e.g. a block when the function is a provided one.
1900 attrs: &mut Vec<Attribute>,
1904 ) -> PResult<'a, Option<P<Block>>> {
1905 let has_semi = if req_body {
1906 self.token.kind == TokenKind::Semi
1908 // Only include `;` in list of expected tokens if body is not required
1909 self.check(&TokenKind::Semi)
1911 let (inner_attrs, body) = if has_semi {
1912 // Include the trailing semicolon in the span of the signature
1913 self.expect_semi()?;
1914 *sig_hi = self.prev_token.span;
1916 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1917 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1918 } else if self.token.kind == token::Eq {
1919 // Recover `fn foo() = $expr;`.
1921 let eq_sp = self.prev_token.span;
1922 let _ = self.parse_expr()?;
1923 self.expect_semi()?; // `;`
1924 let span = eq_sp.to(self.prev_token.span);
1925 self.struct_span_err(span, "function body cannot be `= expression;`")
1926 .multipart_suggestion(
1927 "surround the expression with `{` and `}` instead of `=` and `;`",
1928 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1929 Applicability::MachineApplicable,
1932 (Vec::new(), Some(self.mk_block_err(span)))
1934 let expected = if req_body {
1935 &[token::OpenDelim(token::Brace)][..]
1937 &[token::Semi, token::OpenDelim(token::Brace)]
1939 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
1940 if self.token.kind == token::CloseDelim(token::Brace) {
1941 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1942 // the AST for typechecking.
1943 err.span_label(ident.span, "while parsing this `fn`");
1951 attrs.extend(inner_attrs);
1955 /// Is the current token the start of an `FnHeader` / not a valid parse?
1957 /// `check_pub` adds additional `pub` to the checks in case users place it
1958 /// wrongly, can be used to ensure `pub` never comes after `default`.
1959 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
1960 // We use an over-approximation here.
1961 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1962 // `pub` is added in case users got confused with the ordering like `async pub fn`,
1963 // only if it wasn't preceeded by `default` as `default pub` is invalid.
1964 let quals: &[Symbol] = if check_pub {
1965 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1967 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1969 self.check_keyword(kw::Fn) // Definitely an `fn`.
1970 // `$qual fn` or `$qual $qual`:
1971 || quals.iter().any(|&kw| self.check_keyword(kw))
1972 && self.look_ahead(1, |t| {
1973 // `$qual fn`, e.g. `const fn` or `async fn`.
1974 t.is_keyword(kw::Fn)
1975 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1976 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
1977 // Rule out 2015 `const async: T = val`.
1979 // Rule out unsafe extern block.
1980 && !self.is_unsafe_foreign_mod())
1983 || self.check_keyword(kw::Extern)
1984 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1985 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1988 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1989 /// up to and including the `fn` keyword. The formal grammar is:
1992 /// Extern = "extern" StringLit? ;
1993 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1994 /// FnFrontMatter = FnQual "fn" ;
1997 /// `vis` represents the visibility that was already parsed, if any. Use
1998 /// `Visibility::Inherited` when no visibility is known.
1999 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2000 let sp_start = self.token.span;
2001 let constness = self.parse_constness();
2003 let async_start_sp = self.token.span;
2004 let asyncness = self.parse_asyncness();
2006 let unsafe_start_sp = self.token.span;
2007 let unsafety = self.parse_unsafety();
2009 let ext_start_sp = self.token.span;
2010 let ext = self.parse_extern();
2012 if let Async::Yes { span, .. } = asyncness {
2013 self.ban_async_in_2015(span);
2016 if !self.eat_keyword(kw::Fn) {
2017 // It is possible for `expect_one_of` to recover given the contents of
2018 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2019 // account for this.
2020 match self.expect_one_of(&[], &[]) {
2022 Ok(false) => unreachable!(),
2024 // Qualifier keywords ordering check
2030 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2031 // that the keyword is already present and the second instance should be removed.
2032 let wrong_kw = if self.check_keyword(kw::Const) {
2034 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2035 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2037 } else if self.check_keyword(kw::Async) {
2039 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2040 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2042 } else if self.check_keyword(kw::Unsafe) {
2044 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2045 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2051 // The keyword is already present, suggest removal of the second instance
2052 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2053 let original_kw = self
2054 .span_to_snippet(original_sp)
2055 .expect("Span extracted directly from keyword should always work");
2057 err.span_suggestion(
2058 self.token.uninterpolated_span(),
2059 &format!("`{}` already used earlier, remove this one", original_kw),
2061 Applicability::MachineApplicable,
2063 .span_note(original_sp, &format!("`{}` first seen here", original_kw));
2065 // The keyword has not been seen yet, suggest correct placement in the function front matter
2066 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2067 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2068 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2069 let misplaced_qual_sp = self.token.uninterpolated_span();
2070 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2072 err.span_suggestion(
2073 correct_pos_sp.to(misplaced_qual_sp),
2074 &format!("`{}` must come before `{}`", misplaced_qual, current_qual),
2075 format!("{} {}", misplaced_qual, current_qual),
2076 Applicability::MachineApplicable,
2077 ).note("keyword order for functions declaration is `default`, `pub`, `const`, `async`, `unsafe`, `extern`");
2080 // Recover incorrect visibility order such as `async pub`
2081 else if self.check_keyword(kw::Pub) {
2082 let sp = sp_start.to(self.prev_token.span);
2083 if let Ok(snippet) = self.span_to_snippet(sp) {
2084 let current_vis = match self.parse_visibility(FollowedByType::No) {
2091 let vs = pprust::vis_to_string(¤t_vis);
2092 let vs = vs.trim_end();
2094 // There was no explicit visibility
2095 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2096 err.span_suggestion(
2097 sp_start.to(self.prev_token.span),
2098 &format!("visibility `{}` must come before `{}`", vs, snippet),
2099 format!("{} {}", vs, snippet),
2100 Applicability::MachineApplicable,
2103 // There was an explicit visibility
2105 err.span_suggestion(
2107 "there is already a visibility modifier, remove one",
2109 Applicability::MachineApplicable,
2111 .span_note(orig_vis.span, "explicit visibility first seen here");
2120 Ok(FnHeader { constness, unsafety, asyncness, ext })
2123 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2124 fn ban_async_in_2015(&self, span: Span) {
2125 if span.rust_2015() {
2126 let diag = self.diagnostic();
2127 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2128 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2129 .help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION))
2130 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
2135 /// Parses the parameter list and result type of a function declaration.
2136 pub(super) fn parse_fn_decl(
2139 ret_allow_plus: AllowPlus,
2140 recover_return_sign: RecoverReturnSign,
2141 ) -> PResult<'a, P<FnDecl>> {
2143 inputs: self.parse_fn_params(req_name)?,
2144 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2148 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2149 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2150 let mut first_param = true;
2151 // Parse the arguments, starting out with `self` being allowed...
2152 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2153 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2155 let lo = p.prev_token.span;
2156 // Skip every token until next possible arg or end.
2157 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
2158 // Create a placeholder argument for proper arg count (issue #34264).
2159 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2161 // ...now that we've parsed the first argument, `self` is no longer allowed.
2162 first_param = false;
2165 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2166 self.deduplicate_recovered_params_names(&mut params);
2170 /// Parses a single function parameter.
2172 /// - `self` is syntactically allowed when `first_param` holds.
2173 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2174 let lo = self.token.span;
2175 let attrs = self.parse_outer_attributes()?;
2176 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2177 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2178 if let Some(mut param) = this.parse_self_param()? {
2179 param.attrs = attrs.into();
2180 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2181 return Ok((res?, TrailingToken::None));
2184 let is_name_required = match this.token.kind {
2185 token::DotDotDot => false,
2186 _ => req_name(this.token.span.edition()),
2188 let (pat, ty) = if is_name_required || this.is_named_param() {
2189 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2191 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2193 let mut err = this.unexpected::<()>().unwrap_err();
2194 return if let Some(ident) =
2195 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2198 Ok((dummy_arg(ident), TrailingToken::None))
2204 this.eat_incorrect_doc_comment_for_param_type();
2205 (pat, this.parse_ty_for_param()?)
2207 debug!("parse_param_general ident_to_pat");
2208 let parser_snapshot_before_ty = this.clone();
2209 this.eat_incorrect_doc_comment_for_param_type();
2210 let mut ty = this.parse_ty_for_param();
2212 && this.token != token::Comma
2213 && this.token != token::CloseDelim(token::Paren)
2215 // This wasn't actually a type, but a pattern looking like a type,
2216 // so we are going to rollback and re-parse for recovery.
2217 ty = this.unexpected();
2221 let ident = Ident::new(kw::Empty, this.prev_token.span);
2222 let bm = BindingMode::ByValue(Mutability::Not);
2223 let pat = this.mk_pat_ident(ty.span, bm, ident);
2226 // If this is a C-variadic argument and we hit an error, return the error.
2227 Err(err) if this.token == token::DotDotDot => return Err(err),
2228 // Recover from attempting to parse the argument as a type without pattern.
2231 *this = parser_snapshot_before_ty;
2232 this.recover_arg_parse()?
2237 let span = lo.until(this.token.span);
2241 attrs: attrs.into(),
2242 id: ast::DUMMY_NODE_ID,
2243 is_placeholder: false,
2248 TrailingToken::None,
2253 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2254 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2255 // Extract an identifier *after* having confirmed that the token is one.
2256 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2257 Some((ident, false)) => {
2261 _ => unreachable!(),
2263 // Is `self` `n` tokens ahead?
2264 let is_isolated_self = |this: &Self, n| {
2265 this.is_keyword_ahead(n, &[kw::SelfLower])
2266 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2268 // Is `mut self` `n` tokens ahead?
2269 let is_isolated_mut_self =
2270 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2271 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2272 let parse_self_possibly_typed = |this: &mut Self, m| {
2273 let eself_ident = expect_self_ident(this);
2274 let eself_hi = this.prev_token.span;
2275 let eself = if this.eat(&token::Colon) {
2276 SelfKind::Explicit(this.parse_ty()?, m)
2280 Ok((eself, eself_ident, eself_hi))
2282 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2283 let recover_self_ptr = |this: &mut Self| {
2284 let msg = "cannot pass `self` by raw pointer";
2285 let span = this.token.span;
2286 this.struct_span_err(span, msg).span_label(span, msg).emit();
2288 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2291 // Parse optional `self` parameter of a method.
2292 // Only a limited set of initial token sequences is considered `self` parameters; anything
2293 // else is parsed as a normal function parameter list, so some lookahead is required.
2294 let eself_lo = self.token.span;
2295 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2296 token::BinOp(token::And) => {
2297 let eself = if is_isolated_self(self, 1) {
2300 SelfKind::Region(None, Mutability::Not)
2301 } else if is_isolated_mut_self(self, 1) {
2305 SelfKind::Region(None, Mutability::Mut)
2306 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2309 let lt = self.expect_lifetime();
2310 SelfKind::Region(Some(lt), Mutability::Not)
2311 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2314 let lt = self.expect_lifetime();
2316 SelfKind::Region(Some(lt), Mutability::Mut)
2321 (eself, expect_self_ident(self), self.prev_token.span)
2324 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2326 recover_self_ptr(self)?
2328 // `*mut self` and `*const self`
2329 token::BinOp(token::Star)
2330 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2334 recover_self_ptr(self)?
2336 // `self` and `self: TYPE`
2337 token::Ident(..) if is_isolated_self(self, 0) => {
2338 parse_self_possibly_typed(self, Mutability::Not)?
2340 // `mut self` and `mut self: TYPE`
2341 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2343 parse_self_possibly_typed(self, Mutability::Mut)?
2345 _ => return Ok(None),
2348 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2349 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2352 fn is_named_param(&self) -> bool {
2353 let offset = match self.token.kind {
2354 token::Interpolated(ref nt) => match **nt {
2355 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2358 token::BinOp(token::And) | token::AndAnd => 1,
2359 _ if self.token.is_keyword(kw::Mut) => 1,
2363 self.look_ahead(offset, |t| t.is_ident())
2364 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2367 fn recover_first_param(&mut self) -> &'static str {
2369 .parse_outer_attributes()
2370 .and_then(|_| self.parse_self_param())
2371 .map_err(|e| e.cancel())
2373 Ok(Some(_)) => "method",
2379 enum IsMacroRulesItem {
2380 Yes { has_bang: bool },