1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath};
3 use super::{FollowedByType, Parser, PathStyle};
5 use crate::maybe_whole;
7 use rustc_ast::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
8 use rustc_ast::ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind, Mod};
9 use rustc_ast::ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
10 use rustc_ast::ast::{BindingMode, Block, FnDecl, FnSig, Param, SelfKind};
11 use rustc_ast::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
12 use rustc_ast::ast::{FnHeader, ForeignItem, PathSegment, Visibility, VisibilityKind};
13 use rustc_ast::ast::{MacArgs, MacCall, MacDelimiter};
14 use rustc_ast::ptr::P;
15 use rustc_ast::token::{self, TokenKind};
16 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
17 use rustc_ast_pretty::pprust;
18 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
19 use rustc_span::edition::Edition;
20 use rustc_span::source_map::{self, Span};
21 use rustc_span::symbol::{kw, sym, Symbol};
24 use std::convert::TryFrom;
28 /// Parses a source module as a crate. This is the main entry point for the parser.
29 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
30 let lo = self.token.span;
31 let (module, attrs) = self.parse_mod(&token::Eof)?;
32 let span = lo.to(self.token.span);
33 let proc_macros = Vec::new(); // Filled in by `proc_macro_harness::inject()`.
34 Ok(ast::Crate { attrs, module, span, proc_macros })
37 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
38 fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
39 let id = self.parse_ident()?;
40 let (module, mut inner_attrs) = if self.eat(&token::Semi) {
43 self.expect(&token::OpenDelim(token::Brace))?;
44 self.parse_mod(&token::CloseDelim(token::Brace))?
46 attrs.append(&mut inner_attrs);
47 Ok((id, ItemKind::Mod(module)))
50 /// Parses the contents of a module (inner attributes followed by module items).
51 pub fn parse_mod(&mut self, term: &TokenKind) -> PResult<'a, (Mod, Vec<Attribute>)> {
52 let lo = self.token.span;
53 let attrs = self.parse_inner_attributes()?;
54 let module = self.parse_mod_items(term, lo)?;
58 /// Given a termination token, parses all of the items in a module.
59 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
60 let mut items = vec![];
61 while let Some(item) = self.parse_item()? {
63 self.maybe_consume_incorrect_semicolon(&items);
67 let token_str = super::token_descr(&self.token);
68 if !self.maybe_consume_incorrect_semicolon(&items) {
69 let msg = &format!("expected item, found {}", token_str);
70 let mut err = self.struct_span_err(self.token.span, msg);
71 err.span_label(self.token.span, "expected item");
76 let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_token.span };
78 Ok(Mod { inner: inner_lo.to(hi), items, inline: true })
82 pub(super) type ItemInfo = (Ident, ItemKind);
85 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
86 self.parse_item_(|_| true).map(|i| i.map(P))
89 fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
90 let attrs = self.parse_outer_attributes()?;
91 self.parse_item_common(attrs, true, false, req_name)
94 pub(super) fn parse_item_common(
96 mut attrs: Vec<Attribute>,
100 ) -> PResult<'a, Option<Item>> {
101 maybe_whole!(self, NtItem, |item| {
103 mem::swap(&mut item.attrs, &mut attrs);
104 item.attrs.extend(attrs);
105 Some(item.into_inner())
108 let mut unclosed_delims = vec![];
109 let (mut item, tokens) = self.collect_tokens(|this| {
110 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
111 unclosed_delims.append(&mut this.unclosed_delims);
114 self.unclosed_delims.append(&mut unclosed_delims);
116 // Once we've parsed an item and recorded the tokens we got while
117 // parsing we may want to store `tokens` into the item we're about to
118 // return. Note, though, that we specifically didn't capture tokens
119 // related to outer attributes. The `tokens` field here may later be
120 // used with procedural macros to convert this item back into a token
121 // stream, but during expansion we may be removing attributes as we go
124 // If we've got inner attributes then the `tokens` we've got above holds
125 // these inner attributes. If an inner attribute is expanded we won't
126 // actually remove it from the token stream, so we'll just keep yielding
127 // it (bad!). To work around this case for now we just avoid recording
128 // `tokens` if we detect any inner attributes. This should help keep
129 // expansion correct, but we should fix this bug one day!
130 if let Some(item) = &mut item {
131 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
132 item.tokens = Some(tokens);
138 fn parse_item_common_(
140 mut attrs: Vec<Attribute>,
144 ) -> PResult<'a, Option<Item>> {
145 let lo = self.token.span;
146 let vis = self.parse_visibility(FollowedByType::No)?;
147 let mut def = self.parse_defaultness();
148 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
149 if let Some((ident, kind)) = kind {
150 self.error_on_unconsumed_default(def, &kind);
151 let span = lo.to(self.prev_token.span);
152 let id = DUMMY_NODE_ID;
153 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
154 return Ok(Some(item));
157 // At this point, we have failed to parse an item.
158 self.error_on_unmatched_vis(&vis);
159 self.error_on_unmatched_defaultness(def);
161 self.recover_attrs_no_item(&attrs)?;
166 /// Error in-case a non-inherited visibility was parsed but no item followed.
167 fn error_on_unmatched_vis(&self, vis: &Visibility) {
168 if let VisibilityKind::Inherited = vis.node {
171 let vs = pprust::vis_to_string(&vis);
172 let vs = vs.trim_end();
173 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
174 .span_label(vis.span, "the visibility")
175 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
179 /// Error in-case a `default` was parsed but no item followed.
180 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
181 if let Defaultness::Default(sp) = def {
182 self.struct_span_err(sp, "`default` is not followed by an item")
183 .span_label(sp, "the `default` qualifier")
184 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
189 /// Error in-case `default` was parsed in an in-appropriate context.
190 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
191 if let Defaultness::Default(span) = def {
192 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
193 self.struct_span_err(span, &msg)
194 .span_label(span, "`default` because of this")
195 .note("only associated `fn`, `const`, and `type` items can be `default`")
200 /// Parses one of the items allowed by the flags.
203 attrs: &mut Vec<Attribute>,
204 macros_allowed: bool,
207 def: &mut Defaultness,
209 ) -> PResult<'a, Option<ItemInfo>> {
210 let mut def = || mem::replace(def, Defaultness::Final);
212 let info = if self.eat_keyword(kw::Use) {
214 let tree = self.parse_use_tree()?;
216 (Ident::invalid(), ItemKind::Use(P(tree)))
217 } else if self.check_fn_front_matter() {
219 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name)?;
220 (ident, ItemKind::Fn(def(), sig, generics, body))
221 } else if self.eat_keyword(kw::Extern) {
222 if self.eat_keyword(kw::Crate) {
224 self.parse_item_extern_crate()?
227 self.parse_item_foreign_mod(attrs)?
229 } else if self.is_static_global() {
231 self.bump(); // `static`
232 let m = self.parse_mutability();
233 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
234 (ident, ItemKind::Static(ty, m, expr))
235 } else if let Const::Yes(const_span) = self.parse_constness() {
237 self.recover_const_mut(const_span);
238 let (ident, ty, expr) = self.parse_item_global(None)?;
239 (ident, ItemKind::Const(def(), ty, expr))
240 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
242 self.parse_item_trait(attrs, lo)?
243 } else if self.check_keyword(kw::Impl)
244 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
247 self.parse_item_impl(attrs, def())?
248 } else if self.eat_keyword(kw::Mod) {
250 self.parse_item_mod(attrs)?
251 } else if self.eat_keyword(kw::Type) {
253 self.parse_type_alias(def())?
254 } else if self.eat_keyword(kw::Enum) {
256 self.parse_item_enum()?
257 } else if self.eat_keyword(kw::Struct) {
259 self.parse_item_struct()?
260 } else if self.is_kw_followed_by_ident(kw::Union) {
262 self.bump(); // `union`
263 self.parse_item_union()?
264 } else if self.eat_keyword(kw::Macro) {
266 self.parse_item_decl_macro(lo)?
267 } else if self.is_macro_rules_item() {
269 self.parse_item_macro_rules(vis)?
270 } else if vis.node.is_pub() && self.isnt_macro_invocation() {
271 self.recover_missing_kw_before_item()?;
273 } else if macros_allowed && self.check_path() {
274 // MACRO INVOCATION ITEM
275 (Ident::invalid(), ItemKind::MacCall(self.parse_item_macro(vis)?))
282 /// When parsing a statement, would the start of a path be an item?
283 pub(super) fn is_path_start_item(&mut self) -> bool {
284 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
285 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
286 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
287 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
288 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
291 /// Are we sure this could not possibly be a macro invocation?
292 fn isnt_macro_invocation(&mut self) -> bool {
293 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
296 /// Recover on encountering a struct or method definition where the user
297 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
298 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
299 // Space between `pub` keyword and the identifier
302 // ^^^ `sp` points here
303 let sp = self.prev_token.span.between(self.token.span);
304 let full_sp = self.prev_token.span.to(self.token.span);
305 let ident_sp = self.token.span;
306 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
307 // possible public struct definition where `struct` was forgotten
308 let ident = self.parse_ident().unwrap();
309 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
310 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
311 err.span_suggestion_short(
315 Applicability::MaybeIncorrect, // speculative
318 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
319 let ident = self.parse_ident().unwrap();
321 let kw_name = self.recover_first_param();
322 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
323 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
324 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
326 ("fn", kw_name, false)
327 } else if self.check(&token::OpenDelim(token::Brace)) {
329 ("fn", kw_name, false)
330 } else if self.check(&token::Colon) {
334 ("fn` or `struct", "function or struct", true)
337 let msg = format!("missing `{}` for {} definition", kw, kw_name);
338 let mut err = self.struct_span_err(sp, &msg);
340 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
342 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
343 err.span_suggestion_short(
347 Applicability::MachineApplicable,
350 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
353 "if you meant to call a macro, try",
354 format!("{}!", snippet),
355 // this is the `ambiguous` conditional branch
356 Applicability::MaybeIncorrect,
360 "if you meant to call a macro, remove the `pub` \
361 and add a trailing `!` after the identifier",
366 } else if self.look_ahead(1, |t| *t == token::Lt) {
367 let ident = self.parse_ident().unwrap();
368 self.eat_to_tokens(&[&token::Gt]);
370 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
371 ("fn", self.recover_first_param(), false)
372 } else if self.check(&token::OpenDelim(token::Brace)) {
373 ("struct", "struct", false)
375 ("fn` or `struct", "function or struct", true)
377 let msg = format!("missing `{}` for {} definition", kw, kw_name);
378 let mut err = self.struct_span_err(sp, &msg);
380 err.span_suggestion_short(
382 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
384 Applicability::MachineApplicable,
393 /// Parses an item macro, e.g., `item!();`.
394 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
395 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
396 self.expect(&token::Not)?; // `!`
397 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
398 self.eat_semi_for_macro_if_needed(&args);
399 self.complain_if_pub_macro(vis, false);
400 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
403 /// Recover if we parsed attributes and expected an item but there was none.
404 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
405 let (start, end) = match attrs {
407 [x0 @ xn] | [x0, .., xn] => (x0, xn),
409 let msg = if end.is_doc_comment() {
410 "expected item after doc comment"
412 "expected item after attributes"
414 let mut err = self.struct_span_err(end.span, msg);
415 if end.is_doc_comment() {
416 err.span_label(end.span, "this doc comment doesn't document anything");
418 if let [.., penultimate, _] = attrs {
419 err.span_label(start.span.to(penultimate.span), "other attributes here");
424 fn is_async_fn(&self) -> bool {
425 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
428 fn parse_polarity(&mut self) -> ast::ImplPolarity {
429 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
430 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
432 ast::ImplPolarity::Negative(self.prev_token.span)
434 ast::ImplPolarity::Positive
438 /// Parses an implementation item.
441 /// impl<'a, T> TYPE { /* impl items */ }
442 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
443 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
444 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
447 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
449 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
450 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
454 attrs: &mut Vec<Attribute>,
455 defaultness: Defaultness,
456 ) -> PResult<'a, ItemInfo> {
457 let unsafety = self.parse_unsafety();
458 self.expect_keyword(kw::Impl)?;
460 // First, parse generic parameters if necessary.
461 let mut generics = if self.choose_generics_over_qpath() {
462 self.parse_generics()?
464 let mut generics = Generics::default();
466 // /\ this is where `generics.span` should point when there are no type params.
467 generics.span = self.prev_token.span.shrink_to_hi();
471 let constness = self.parse_constness();
472 if let Const::Yes(span) = constness {
473 self.sess.gated_spans.gate(sym::const_trait_impl, span);
476 let polarity = self.parse_polarity();
478 // Parse both types and traits as a type, then reinterpret if necessary.
479 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
480 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
482 let span = self.prev_token.span.between(self.token.span);
483 self.struct_span_err(span, "missing trait in a trait impl").emit();
484 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
489 // If `for` is missing we try to recover.
490 let has_for = self.eat_keyword(kw::For);
491 let missing_for_span = self.prev_token.span.between(self.token.span);
493 let ty_second = if self.token == token::DotDot {
494 // We need to report this error after `cfg` expansion for compatibility reasons
495 self.bump(); // `..`, do not add it to expected tokens
496 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
497 } else if has_for || self.token.can_begin_type() {
498 Some(self.parse_ty()?)
503 generics.where_clause = self.parse_where_clause()?;
505 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
507 let item_kind = match ty_second {
509 // impl Trait for Type
511 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
512 .span_suggestion_short(
516 Applicability::MachineApplicable,
521 let ty_first = ty_first.into_inner();
522 let path = match ty_first.kind {
523 // This notably includes paths passed through `ty` macro fragments (#46438).
524 TyKind::Path(None, path) => path,
526 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
527 err_path(ty_first.span)
530 let trait_ref = TraitRef { path, ref_id: ty_first.id };
538 of_trait: Some(trait_ref),
558 Ok((Ident::invalid(), item_kind))
561 fn parse_item_list<T>(
563 attrs: &mut Vec<Attribute>,
564 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
565 ) -> PResult<'a, Vec<T>> {
566 let open_brace_span = self.token.span;
567 self.expect(&token::OpenDelim(token::Brace))?;
568 attrs.append(&mut self.parse_inner_attributes()?);
570 let mut items = Vec::new();
571 while !self.eat(&token::CloseDelim(token::Brace)) {
572 if self.recover_doc_comment_before_brace() {
575 match parse_item(self) {
577 // We have to bail or we'll potentially never make progress.
578 let non_item_span = self.token.span;
579 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
580 self.struct_span_err(non_item_span, "non-item in item list")
581 .span_label(open_brace_span, "item list starts here")
582 .span_label(non_item_span, "non-item starts here")
583 .span_label(self.prev_token.span, "item list ends here")
587 Ok(Some(item)) => items.extend(item),
589 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
590 err.span_label(open_brace_span, "while parsing this item list starting here")
591 .span_label(self.prev_token.span, "the item list ends here")
600 /// Recover on a doc comment before `}`.
601 fn recover_doc_comment_before_brace(&mut self) -> bool {
602 if let token::DocComment(_) = self.token.kind {
603 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
608 "found a documentation comment that doesn't document anything",
610 .span_label(self.token.span, "this doc comment doesn't document anything")
612 "doc comments must come before what they document, maybe a \
613 comment was intended with `//`?",
623 /// Parses defaultness (i.e., `default` or nothing).
624 fn parse_defaultness(&mut self) -> Defaultness {
625 // We are interested in `default` followed by another identifier.
626 // However, we must avoid keywords that occur as binary operators.
627 // Currently, the only applicable keyword is `as` (`default as Ty`).
628 if self.check_keyword(kw::Default)
629 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
631 self.bump(); // `default`
632 Defaultness::Default(self.prev_token.uninterpolated_span())
638 /// Is this an `(unsafe auto? | auto) trait` item?
639 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
641 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
643 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
646 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
647 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
648 let unsafety = self.parse_unsafety();
649 // Parse optional `auto` prefix.
650 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
652 self.expect_keyword(kw::Trait)?;
653 let ident = self.parse_ident()?;
654 let mut tps = self.parse_generics()?;
656 // Parse optional colon and supertrait bounds.
657 let had_colon = self.eat(&token::Colon);
658 let span_at_colon = self.prev_token.span;
659 let bounds = if had_colon {
660 self.parse_generic_bounds(Some(self.prev_token.span))?
665 let span_before_eq = self.prev_token.span;
666 if self.eat(&token::Eq) {
667 // It's a trait alias.
669 let span = span_at_colon.to(span_before_eq);
670 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
673 let bounds = self.parse_generic_bounds(None)?;
674 tps.where_clause = self.parse_where_clause()?;
677 let whole_span = lo.to(self.prev_token.span);
678 if is_auto == IsAuto::Yes {
679 let msg = "trait aliases cannot be `auto`";
680 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
682 if let Unsafe::Yes(_) = unsafety {
683 let msg = "trait aliases cannot be `unsafe`";
684 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
687 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
689 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
691 // It's a normal trait.
692 tps.where_clause = self.parse_where_clause()?;
693 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
694 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
698 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
699 self.parse_assoc_item(|_| true)
702 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
703 self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
706 /// Parses associated items.
707 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
708 Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
709 let kind = match AssocItemKind::try_from(kind) {
711 Err(kind) => match kind {
712 ItemKind::Static(a, _, b) => {
713 self.struct_span_err(span, "associated `static` items are not allowed")
715 AssocItemKind::Const(Defaultness::Final, a, b)
717 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
720 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
724 /// Parses a `type` alias with the following grammar:
726 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
728 /// The `"type"` has already been eaten.
729 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
730 let ident = self.parse_ident()?;
731 let mut generics = self.parse_generics()?;
733 // Parse optional colon and param bounds.
735 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
736 generics.where_clause = self.parse_where_clause()?;
738 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
741 Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
744 /// Parses a `UseTree`.
747 /// USE_TREE = [`::`] `*` |
748 /// [`::`] `{` USE_TREE_LIST `}` |
750 /// PATH `::` `{` USE_TREE_LIST `}` |
751 /// PATH [`as` IDENT]
753 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
754 let lo = self.token.span;
756 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
757 let kind = if self.check(&token::OpenDelim(token::Brace))
758 || self.check(&token::BinOp(token::Star))
759 || self.is_import_coupler()
761 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
762 let mod_sep_ctxt = self.token.span.ctxt();
763 if self.eat(&token::ModSep) {
766 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
769 self.parse_use_tree_glob_or_nested()?
771 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
772 prefix = self.parse_path(PathStyle::Mod)?;
774 if self.eat(&token::ModSep) {
775 self.parse_use_tree_glob_or_nested()?
777 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
781 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
784 /// Parses `*` or `{...}`.
785 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
786 Ok(if self.eat(&token::BinOp(token::Star)) {
789 UseTreeKind::Nested(self.parse_use_tree_list()?)
793 /// Parses a `UseTreeKind::Nested(list)`.
796 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
798 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
799 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
803 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
804 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
807 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
808 match self.token.ident() {
809 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
813 _ => self.parse_ident(),
817 /// Parses `extern crate` links.
822 /// extern crate foo;
823 /// extern crate bar as foo;
825 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
826 // Accept `extern crate name-like-this` for better diagnostics
827 let orig_name = self.parse_crate_name_with_dashes()?;
828 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
829 (rename, Some(orig_name.name))
834 Ok((item_name, ItemKind::ExternCrate(orig_name)))
837 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
838 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
839 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
841 let mut ident = if self.token.is_keyword(kw::SelfLower) {
842 self.parse_path_segment_ident()
846 let mut idents = vec![];
847 let mut replacement = vec![];
848 let mut fixed_crate_name = false;
849 // Accept `extern crate name-like-this` for better diagnostics.
850 let dash = token::BinOp(token::BinOpToken::Minus);
851 if self.token == dash {
852 // Do not include `-` as part of the expected tokens list.
853 while self.eat(&dash) {
854 fixed_crate_name = true;
855 replacement.push((self.prev_token.span, "_".to_string()));
856 idents.push(self.parse_ident()?);
859 if fixed_crate_name {
860 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
861 let mut fixed_name = format!("{}", ident.name);
863 fixed_name.push_str(&format!("_{}", part.name));
865 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
867 self.struct_span_err(fixed_name_sp, error_msg)
868 .span_label(fixed_name_sp, "dash-separated idents are not valid")
869 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
875 /// Parses `extern` for foreign ABIs modules.
877 /// `extern` is expected to have been consumed before calling this method.
881 /// ```ignore (only-for-syntax-highlight)
885 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
886 let abi = self.parse_abi(); // ABI?
887 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
888 let module = ast::ForeignMod { abi, items };
889 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
892 /// Parses a foreign item (one in an `extern { ... }` block).
893 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
894 Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
895 let kind = match ForeignItemKind::try_from(kind) {
897 Err(kind) => match kind {
898 ItemKind::Const(_, a, b) => {
899 self.error_on_foreign_const(span, ident);
900 ForeignItemKind::Static(a, Mutability::Not, b)
902 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
905 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
909 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
910 let span = self.sess.source_map().def_span(span);
911 let msg = format!("{} is not supported in {}", kind.descr(), ctx);
912 self.struct_span_err(span, &msg).emit();
916 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
917 self.struct_span_err(ident.span, "extern items cannot be `const`")
919 span.with_hi(ident.span.lo()),
920 "try using a static value",
921 "static ".to_string(),
922 Applicability::MachineApplicable,
924 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
928 fn is_static_global(&mut self) -> bool {
929 if self.check_keyword(kw::Static) {
930 // Check if this could be a closure.
931 !self.look_ahead(1, |token| {
932 if token.is_keyword(kw::Move) {
936 token::BinOp(token::Or) | token::OrOr => true,
945 /// Recover on `const mut` with `const` already eaten.
946 fn recover_const_mut(&mut self, const_span: Span) {
947 if self.eat_keyword(kw::Mut) {
948 let span = self.prev_token.span;
949 self.struct_span_err(span, "const globals cannot be mutable")
950 .span_label(span, "cannot be mutable")
953 "you might want to declare a static instead",
955 Applicability::MaybeIncorrect,
961 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
962 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
964 /// When `m` is `"const"`, `$ident` may also be `"_"`.
965 fn parse_item_global(
967 m: Option<Mutability>,
968 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
969 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
971 // Parse the type of a `const` or `static mut?` item.
972 // That is, the `":" $ty` fragment.
973 let ty = if self.eat(&token::Colon) {
976 self.recover_missing_const_type(id, m)
979 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
984 /// We were supposed to parse `:` but the `:` was missing.
985 /// This means that the type is missing.
986 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
987 // Construct the error and stash it away with the hope
988 // that typeck will later enrich the error with a type.
990 Some(Mutability::Mut) => "static mut",
991 Some(Mutability::Not) => "static",
994 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
997 "provide a type for the item",
998 format!("{}: <type>", id),
999 Applicability::HasPlaceholders,
1001 err.stash(id.span, StashKey::ItemNoType);
1003 // The user intended that the type be inferred,
1004 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1005 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1008 /// Parses an enum declaration.
1009 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1010 let id = self.parse_ident()?;
1011 let mut generics = self.parse_generics()?;
1012 generics.where_clause = self.parse_where_clause()?;
1015 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1016 self.recover_stmt();
1020 let enum_definition =
1021 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1022 Ok((id, ItemKind::Enum(enum_definition, generics)))
1025 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1026 let variant_attrs = self.parse_outer_attributes()?;
1027 let vlo = self.token.span;
1029 let vis = self.parse_visibility(FollowedByType::No)?;
1030 if !self.recover_nested_adt_item(kw::Enum)? {
1033 let ident = self.parse_ident()?;
1035 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1036 // Parse a struct variant.
1037 let (fields, recovered) = self.parse_record_struct_body()?;
1038 VariantData::Struct(fields, recovered)
1039 } else if self.check(&token::OpenDelim(token::Paren)) {
1040 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1042 VariantData::Unit(DUMMY_NODE_ID)
1046 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1048 let vr = ast::Variant {
1052 attrs: variant_attrs,
1055 span: vlo.to(self.prev_token.span),
1056 is_placeholder: false,
1062 /// Parses `struct Foo { ... }`.
1063 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1064 let class_name = self.parse_ident()?;
1066 let mut generics = self.parse_generics()?;
1068 // There is a special case worth noting here, as reported in issue #17904.
1069 // If we are parsing a tuple struct it is the case that the where clause
1070 // should follow the field list. Like so:
1072 // struct Foo<T>(T) where T: Copy;
1074 // If we are parsing a normal record-style struct it is the case
1075 // that the where clause comes before the body, and after the generics.
1076 // So if we look ahead and see a brace or a where-clause we begin
1077 // parsing a record style struct.
1079 // Otherwise if we look ahead and see a paren we parse a tuple-style
1082 let vdata = if self.token.is_keyword(kw::Where) {
1083 generics.where_clause = self.parse_where_clause()?;
1084 if self.eat(&token::Semi) {
1085 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1086 VariantData::Unit(DUMMY_NODE_ID)
1088 // If we see: `struct Foo<T> where T: Copy { ... }`
1089 let (fields, recovered) = self.parse_record_struct_body()?;
1090 VariantData::Struct(fields, recovered)
1092 // No `where` so: `struct Foo<T>;`
1093 } else if self.eat(&token::Semi) {
1094 VariantData::Unit(DUMMY_NODE_ID)
1095 // Record-style struct definition
1096 } else if self.token == token::OpenDelim(token::Brace) {
1097 let (fields, recovered) = self.parse_record_struct_body()?;
1098 VariantData::Struct(fields, recovered)
1099 // Tuple-style struct definition with optional where-clause.
1100 } else if self.token == token::OpenDelim(token::Paren) {
1101 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1102 generics.where_clause = self.parse_where_clause()?;
1103 self.expect_semi()?;
1106 let token_str = super::token_descr(&self.token);
1108 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1111 let mut err = self.struct_span_err(self.token.span, msg);
1112 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1116 Ok((class_name, ItemKind::Struct(vdata, generics)))
1119 /// Parses `union Foo { ... }`.
1120 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1121 let class_name = self.parse_ident()?;
1123 let mut generics = self.parse_generics()?;
1125 let vdata = if self.token.is_keyword(kw::Where) {
1126 generics.where_clause = self.parse_where_clause()?;
1127 let (fields, recovered) = self.parse_record_struct_body()?;
1128 VariantData::Struct(fields, recovered)
1129 } else if self.token == token::OpenDelim(token::Brace) {
1130 let (fields, recovered) = self.parse_record_struct_body()?;
1131 VariantData::Struct(fields, recovered)
1133 let token_str = super::token_descr(&self.token);
1134 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1135 let mut err = self.struct_span_err(self.token.span, msg);
1136 err.span_label(self.token.span, "expected `where` or `{` after union name");
1140 Ok((class_name, ItemKind::Union(vdata, generics)))
1143 fn parse_record_struct_body(
1145 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1146 let mut fields = Vec::new();
1147 let mut recovered = false;
1148 if self.eat(&token::OpenDelim(token::Brace)) {
1149 while self.token != token::CloseDelim(token::Brace) {
1150 let field = self.parse_struct_decl_field().map_err(|e| {
1151 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1156 Ok(field) => fields.push(field),
1163 self.eat(&token::CloseDelim(token::Brace));
1165 let token_str = super::token_descr(&self.token);
1166 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1167 let mut err = self.struct_span_err(self.token.span, msg);
1168 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1172 Ok((fields, recovered))
1175 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1176 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1177 // Unit like structs are handled in parse_item_struct function
1178 self.parse_paren_comma_seq(|p| {
1179 let attrs = p.parse_outer_attributes()?;
1180 let lo = p.token.span;
1181 let vis = p.parse_visibility(FollowedByType::Yes)?;
1182 let ty = p.parse_ty()?;
1184 span: lo.to(ty.span),
1190 is_placeholder: false,
1196 /// Parses an element of a struct declaration.
1197 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1198 let attrs = self.parse_outer_attributes()?;
1199 let lo = self.token.span;
1200 let vis = self.parse_visibility(FollowedByType::No)?;
1201 self.parse_single_struct_field(lo, vis, attrs)
1204 /// Parses a structure field declaration.
1205 fn parse_single_struct_field(
1209 attrs: Vec<Attribute>,
1210 ) -> PResult<'a, StructField> {
1211 let mut seen_comma: bool = false;
1212 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1213 if self.token == token::Comma {
1216 match self.token.kind {
1220 token::CloseDelim(token::Brace) => {}
1221 token::DocComment(_) => {
1222 let previous_span = self.prev_token.span;
1223 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1224 self.bump(); // consume the doc comment
1225 let comma_after_doc_seen = self.eat(&token::Comma);
1226 // `seen_comma` is always false, because we are inside doc block
1227 // condition is here to make code more readable
1228 if !seen_comma && comma_after_doc_seen {
1231 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1235 let sp = self.sess.source_map().next_point(previous_span);
1236 err.span_suggestion(
1238 "missing comma here",
1240 Applicability::MachineApplicable,
1247 let sp = self.prev_token.span.shrink_to_hi();
1248 let mut err = self.struct_span_err(
1250 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1252 if self.token.is_ident() {
1253 // This is likely another field; emit the diagnostic and keep going
1254 err.span_suggestion(
1256 "try adding a comma",
1258 Applicability::MachineApplicable,
1269 /// Parses a structure field.
1270 fn parse_name_and_ty(
1274 attrs: Vec<Attribute>,
1275 ) -> PResult<'a, StructField> {
1276 let name = self.parse_ident()?;
1277 self.expect(&token::Colon)?;
1278 let ty = self.parse_ty()?;
1280 span: lo.to(self.prev_token.span),
1286 is_placeholder: false,
1290 /// Parses a declarative macro 2.0 definition.
1291 /// The `macro` keyword has already been parsed.
1293 /// MacBody = "{" TOKEN_STREAM "}" ;
1294 /// MacParams = "(" TOKEN_STREAM ")" ;
1295 /// DeclMac = "macro" Ident MacParams? MacBody ;
1297 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1298 let ident = self.parse_ident()?;
1299 let body = if self.check(&token::OpenDelim(token::Brace)) {
1300 self.parse_mac_args()? // `MacBody`
1301 } else if self.check(&token::OpenDelim(token::Paren)) {
1302 let params = self.parse_token_tree(); // `MacParams`
1303 let pspan = params.span();
1304 if !self.check(&token::OpenDelim(token::Brace)) {
1305 return self.unexpected();
1307 let body = self.parse_token_tree(); // `MacBody`
1308 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1309 let bspan = body.span();
1310 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1311 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1312 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1313 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1315 return self.unexpected();
1318 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1319 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1322 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1323 fn is_macro_rules_item(&mut self) -> bool {
1324 self.check_keyword(kw::MacroRules)
1325 && self.look_ahead(1, |t| *t == token::Not)
1326 && self.look_ahead(2, |t| t.is_ident())
1329 /// Parses a `macro_rules! foo { ... }` declarative macro.
1330 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1331 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1332 self.expect(&token::Not)?; // `!`
1334 let ident = self.parse_ident()?;
1335 let body = self.parse_mac_args()?;
1336 self.eat_semi_for_macro_if_needed(&body);
1337 self.complain_if_pub_macro(vis, true);
1339 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1342 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1343 /// If that's not the case, emit an error.
1344 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1345 if let VisibilityKind::Inherited = vis.node {
1349 let vstr = pprust::vis_to_string(vis);
1350 let vstr = vstr.trim_end();
1352 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1353 self.struct_span_err(vis.span, &msg)
1356 "try exporting the macro",
1357 "#[macro_export]".to_owned(),
1358 Applicability::MaybeIncorrect, // speculative
1362 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1365 "remove the visibility",
1367 Applicability::MachineApplicable,
1369 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1374 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1375 if args.need_semicolon() && !self.eat(&token::Semi) {
1376 self.report_invalid_macro_expansion_item(args);
1380 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1381 let span = args.span().expect("undelimited macro call");
1382 let mut err = self.struct_span_err(
1384 "macros that expand to items must be delimited with braces or followed by a semicolon",
1386 if self.unclosed_delims.is_empty() {
1387 let DelimSpan { open, close } = match args {
1388 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1389 MacArgs::Delimited(dspan, ..) => *dspan,
1391 err.multipart_suggestion(
1392 "change the delimiters to curly braces",
1393 vec![(open, "{".to_string()), (close, '}'.to_string())],
1394 Applicability::MaybeIncorrect,
1397 err.span_suggestion(
1399 "change the delimiters to curly braces",
1400 " { /* items */ }".to_string(),
1401 Applicability::HasPlaceholders,
1404 err.span_suggestion(
1405 span.shrink_to_hi(),
1408 Applicability::MaybeIncorrect,
1413 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1414 /// it is, we try to parse the item and report error about nested types.
1415 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1416 if (self.token.is_keyword(kw::Enum)
1417 || self.token.is_keyword(kw::Struct)
1418 || self.token.is_keyword(kw::Union))
1419 && self.look_ahead(1, |t| t.is_ident())
1421 let kw_token = self.token.clone();
1422 let kw_str = pprust::token_to_string(&kw_token);
1423 let item = self.parse_item()?;
1425 self.struct_span_err(
1427 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1431 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1433 Applicability::MaybeIncorrect,
1436 // We successfully parsed the item but we must inform the caller about nested problem.
1443 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1445 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1446 type ReqName = fn(Edition) -> bool;
1448 /// Parsing of functions and methods.
1449 impl<'a> Parser<'a> {
1450 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1453 attrs: &mut Vec<Attribute>,
1455 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1456 let header = self.parse_fn_front_matter()?; // `const ... fn`
1457 let ident = self.parse_ident()?; // `foo`
1458 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1459 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1460 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1461 let body = self.parse_fn_body(attrs)?; // `;` or `{ ... }`.
1462 Ok((ident, FnSig { header, decl }, generics, body))
1465 /// Parse the "body" of a function.
1466 /// This can either be `;` when there's no body,
1467 /// or e.g. a block when the function is a provided one.
1468 fn parse_fn_body(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, Option<P<Block>>> {
1469 let (inner_attrs, body) = if self.check(&token::Semi) {
1472 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1473 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1474 } else if self.token.kind == token::Eq {
1475 // Recover `fn foo() = $expr;`.
1477 let eq_sp = self.prev_token.span;
1478 let _ = self.parse_expr()?;
1479 self.expect_semi()?; // `;`
1480 let span = eq_sp.to(self.prev_token.span);
1481 self.struct_span_err(span, "function body cannot be `= expression;`")
1482 .multipart_suggestion(
1483 "surround the expression with `{` and `}` instead of `=` and `;`",
1484 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1485 Applicability::MachineApplicable,
1488 (Vec::new(), Some(self.mk_block_err(span)))
1490 return self.expected_semi_or_open_brace();
1492 attrs.extend(inner_attrs);
1496 /// Is the current token the start of an `FnHeader` / not a valid parse?
1497 fn check_fn_front_matter(&mut self) -> bool {
1498 // We use an over-approximation here.
1499 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1500 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1501 self.check_keyword(kw::Fn) // Definitely an `fn`.
1502 // `$qual fn` or `$qual $qual`:
1503 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1504 && self.look_ahead(1, |t| {
1505 // ...qualified and then `fn`, e.g. `const fn`.
1506 t.is_keyword(kw::Fn)
1507 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1508 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1511 || self.check_keyword(kw::Extern)
1512 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1513 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1516 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1517 /// up to and including the `fn` keyword. The formal grammar is:
1520 /// Extern = "extern" StringLit ;
1521 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1522 /// FnFrontMatter = FnQual? "fn" ;
1524 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1525 let constness = self.parse_constness();
1526 let asyncness = self.parse_asyncness();
1527 let unsafety = self.parse_unsafety();
1528 let ext = self.parse_extern()?;
1530 if let Async::Yes { span, .. } = asyncness {
1531 self.ban_async_in_2015(span);
1534 if !self.eat_keyword(kw::Fn) {
1535 // It is possible for `expect_one_of` to recover given the contents of
1536 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1537 // account for this.
1538 if !self.expect_one_of(&[], &[])? {
1543 Ok(FnHeader { constness, unsafety, asyncness, ext })
1546 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1547 fn ban_async_in_2015(&self, span: Span) {
1548 if span.rust_2015() {
1549 let diag = self.diagnostic();
1550 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1551 .note("to use `async fn`, switch to Rust 2018")
1552 .help("set `edition = \"2018\"` in `Cargo.toml`")
1553 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1558 /// Parses the parameter list and result type of a function declaration.
1559 pub(super) fn parse_fn_decl(
1562 ret_allow_plus: AllowPlus,
1563 ) -> PResult<'a, P<FnDecl>> {
1565 inputs: self.parse_fn_params(req_name)?,
1566 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1570 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1571 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1572 let mut first_param = true;
1573 // Parse the arguments, starting out with `self` being allowed...
1574 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1575 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1577 let lo = p.prev_token.span;
1578 // Skip every token until next possible arg or end.
1579 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1580 // Create a placeholder argument for proper arg count (issue #34264).
1581 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_token.span))))
1583 // ...now that we've parsed the first argument, `self` is no longer allowed.
1584 first_param = false;
1587 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1588 self.deduplicate_recovered_params_names(&mut params);
1592 /// Parses a single function parameter.
1594 /// - `self` is syntactically allowed when `first_param` holds.
1595 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1596 let lo = self.token.span;
1597 let attrs = self.parse_outer_attributes()?;
1599 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1600 if let Some(mut param) = self.parse_self_param()? {
1601 param.attrs = attrs.into();
1602 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1605 let is_name_required = match self.token.kind {
1606 token::DotDotDot => false,
1607 _ => req_name(self.token.span.edition()),
1609 let (pat, ty) = if is_name_required || self.is_named_param() {
1610 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1612 let pat = self.parse_fn_param_pat()?;
1613 if let Err(mut err) = self.expect(&token::Colon) {
1614 return if let Some(ident) =
1615 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1618 Ok(dummy_arg(ident))
1624 self.eat_incorrect_doc_comment_for_param_type();
1625 (pat, self.parse_ty_for_param()?)
1627 debug!("parse_param_general ident_to_pat");
1628 let parser_snapshot_before_ty = self.clone();
1629 self.eat_incorrect_doc_comment_for_param_type();
1630 let mut ty = self.parse_ty_for_param();
1632 && self.token != token::Comma
1633 && self.token != token::CloseDelim(token::Paren)
1635 // This wasn't actually a type, but a pattern looking like a type,
1636 // so we are going to rollback and re-parse for recovery.
1637 ty = self.unexpected();
1641 let ident = Ident::new(kw::Invalid, self.prev_token.span);
1642 let bm = BindingMode::ByValue(Mutability::Not);
1643 let pat = self.mk_pat_ident(ty.span, bm, ident);
1646 // If this is a C-variadic argument and we hit an error, return the error.
1647 Err(err) if self.token == token::DotDotDot => return Err(err),
1648 // Recover from attempting to parse the argument as a type without pattern.
1651 mem::replace(self, parser_snapshot_before_ty);
1652 self.recover_arg_parse()?
1657 let span = lo.to(self.token.span);
1660 attrs: attrs.into(),
1661 id: ast::DUMMY_NODE_ID,
1662 is_placeholder: false,
1669 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1670 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1671 // Extract an identifier *after* having confirmed that the token is one.
1672 let expect_self_ident = |this: &mut Self| match this.token.ident() {
1673 Some((ident, false)) => {
1677 _ => unreachable!(),
1679 // Is `self` `n` tokens ahead?
1680 let is_isolated_self = |this: &Self, n| {
1681 this.is_keyword_ahead(n, &[kw::SelfLower])
1682 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1684 // Is `mut self` `n` tokens ahead?
1685 let is_isolated_mut_self =
1686 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1687 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1688 let parse_self_possibly_typed = |this: &mut Self, m| {
1689 let eself_ident = expect_self_ident(this);
1690 let eself_hi = this.prev_token.span;
1691 let eself = if this.eat(&token::Colon) {
1692 SelfKind::Explicit(this.parse_ty()?, m)
1696 Ok((eself, eself_ident, eself_hi))
1698 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1699 let recover_self_ptr = |this: &mut Self| {
1700 let msg = "cannot pass `self` by raw pointer";
1701 let span = this.token.span;
1702 this.struct_span_err(span, msg).span_label(span, msg).emit();
1704 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
1707 // Parse optional `self` parameter of a method.
1708 // Only a limited set of initial token sequences is considered `self` parameters; anything
1709 // else is parsed as a normal function parameter list, so some lookahead is required.
1710 let eself_lo = self.token.span;
1711 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
1712 token::BinOp(token::And) => {
1713 let eself = if is_isolated_self(self, 1) {
1716 SelfKind::Region(None, Mutability::Not)
1717 } else if is_isolated_mut_self(self, 1) {
1721 SelfKind::Region(None, Mutability::Mut)
1722 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1725 let lt = self.expect_lifetime();
1726 SelfKind::Region(Some(lt), Mutability::Not)
1727 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1730 let lt = self.expect_lifetime();
1732 SelfKind::Region(Some(lt), Mutability::Mut)
1737 (eself, expect_self_ident(self), self.prev_token.span)
1740 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1742 recover_self_ptr(self)?
1744 // `*mut self` and `*const self`
1745 token::BinOp(token::Star)
1746 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1750 recover_self_ptr(self)?
1752 // `self` and `self: TYPE`
1753 token::Ident(..) if is_isolated_self(self, 0) => {
1754 parse_self_possibly_typed(self, Mutability::Not)?
1756 // `mut self` and `mut self: TYPE`
1757 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1759 parse_self_possibly_typed(self, Mutability::Mut)?
1761 _ => return Ok(None),
1764 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1765 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1768 fn is_named_param(&self) -> bool {
1769 let offset = match self.token.kind {
1770 token::Interpolated(ref nt) => match **nt {
1771 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1774 token::BinOp(token::And) | token::AndAnd => 1,
1775 _ if self.token.is_keyword(kw::Mut) => 1,
1779 self.look_ahead(offset, |t| t.is_ident())
1780 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1783 fn recover_first_param(&mut self) -> &'static str {
1785 .parse_outer_attributes()
1786 .and_then(|_| self.parse_self_param())
1787 .map_err(|mut e| e.cancel())
1789 Ok(Some(_)) => "method",