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_pretty::pprust;
8 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
9 use rustc_span::edition::Edition;
10 use rustc_span::source_map::{self, Span};
11 use rustc_span::symbol::{kw, sym, Symbol};
12 use syntax::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
13 use syntax::ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind};
14 use syntax::ast::{Async, Const, Defaultness, IsAuto, PathSegment, Unsafe, UseTree, UseTreeKind};
15 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
16 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
17 use syntax::ast::{FnHeader, ForeignItem, Mutability, Visibility, VisibilityKind};
20 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
25 pub(super) type ItemInfo = (Ident, ItemKind);
28 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
29 self.parse_item_(|_| true).map(|i| i.map(P))
32 fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
33 let attrs = self.parse_outer_attributes()?;
34 self.parse_item_common(attrs, true, false, req_name)
37 pub(super) fn parse_item_common(
39 mut attrs: Vec<Attribute>,
43 ) -> PResult<'a, Option<Item>> {
44 maybe_whole!(self, NtItem, |item| {
46 mem::swap(&mut item.attrs, &mut attrs);
47 item.attrs.extend(attrs);
48 Some(item.into_inner())
51 let mut unclosed_delims = vec![];
52 let (mut item, tokens) = self.collect_tokens(|this| {
53 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
54 unclosed_delims.append(&mut this.unclosed_delims);
57 self.unclosed_delims.append(&mut unclosed_delims);
59 // Once we've parsed an item and recorded the tokens we got while
60 // parsing we may want to store `tokens` into the item we're about to
61 // return. Note, though, that we specifically didn't capture tokens
62 // related to outer attributes. The `tokens` field here may later be
63 // used with procedural macros to convert this item back into a token
64 // stream, but during expansion we may be removing attributes as we go
67 // If we've got inner attributes then the `tokens` we've got above holds
68 // these inner attributes. If an inner attribute is expanded we won't
69 // actually remove it from the token stream, so we'll just keep yielding
70 // it (bad!). To work around this case for now we just avoid recording
71 // `tokens` if we detect any inner attributes. This should help keep
72 // expansion correct, but we should fix this bug one day!
73 if let Some(item) = &mut item {
74 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
75 item.tokens = Some(tokens);
81 fn parse_item_common_(
83 mut attrs: Vec<Attribute>,
87 ) -> PResult<'a, Option<Item>> {
88 let lo = self.token.span;
89 let vis = self.parse_visibility(FollowedByType::No)?;
90 let mut def = self.parse_defaultness();
91 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
92 if let Some((ident, kind)) = kind {
93 self.error_on_unconsumed_default(def, &kind);
94 let span = lo.to(self.prev_span);
95 let id = DUMMY_NODE_ID;
96 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
97 return Ok(Some(item));
100 // At this point, we have failed to parse an item.
101 self.error_on_unmatched_vis(&vis);
102 self.error_on_unmatched_defaultness(def);
104 self.recover_attrs_no_item(&attrs)?;
109 /// Error in-case a non-inherited visibility was parsed but no item followed.
110 fn error_on_unmatched_vis(&self, vis: &Visibility) {
111 if let VisibilityKind::Inherited = vis.node {
114 let vs = pprust::vis_to_string(&vis);
115 let vs = vs.trim_end();
116 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
117 .span_label(vis.span, "the visibility")
118 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
122 /// Error in-case a `default` was parsed but no item followed.
123 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
124 if let Defaultness::Default(sp) = def {
125 self.struct_span_err(sp, "`default` is not followed by an item")
126 .span_label(sp, "the `default` qualifier")
127 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
132 /// Error in-case `default` was parsed in an in-appropriate context.
133 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
134 if let Defaultness::Default(span) = def {
135 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
136 self.struct_span_err(span, &msg)
137 .span_label(span, "`default` because of this")
138 .note("only associated `fn`, `const`, and `type` items can be `default`")
143 /// Parses one of the items allowed by the flags.
146 attrs: &mut Vec<Attribute>,
147 macros_allowed: bool,
150 def: &mut Defaultness,
152 ) -> PResult<'a, Option<ItemInfo>> {
153 let mut def = || mem::replace(def, Defaultness::Final);
155 let info = if self.eat_keyword(kw::Use) {
157 let tree = self.parse_use_tree()?;
159 (Ident::invalid(), ItemKind::Use(P(tree)))
160 } else if self.check_fn_front_matter() {
162 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name)?;
163 (ident, ItemKind::Fn(def(), sig, generics, body))
164 } else if self.eat_keyword(kw::Extern) {
165 if self.eat_keyword(kw::Crate) {
167 self.parse_item_extern_crate()?
170 self.parse_item_foreign_mod(attrs)?
172 } else if self.is_static_global() {
174 self.bump(); // `static`
175 let m = self.parse_mutability();
176 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
177 (ident, ItemKind::Static(ty, m, expr))
178 } else if let Const::Yes(const_span) = self.parse_constness() {
180 self.recover_const_mut(const_span);
181 let (ident, ty, expr) = self.parse_item_global(None)?;
182 (ident, ItemKind::Const(def(), ty, expr))
183 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
185 self.parse_item_trait(attrs, lo)?
186 } else if self.check_keyword(kw::Impl)
187 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
190 self.parse_item_impl(attrs, def())?
191 } else if self.eat_keyword(kw::Mod) {
193 self.parse_item_mod(attrs)?
194 } else if self.eat_keyword(kw::Type) {
196 self.parse_type_alias(def())?
197 } else if self.eat_keyword(kw::Enum) {
199 self.parse_item_enum()?
200 } else if self.eat_keyword(kw::Struct) {
202 self.parse_item_struct()?
203 } else if self.is_kw_followed_by_ident(kw::Union) {
205 self.bump(); // `union`
206 self.parse_item_union()?
207 } else if self.eat_keyword(kw::Macro) {
209 self.parse_item_decl_macro(lo)?
210 } else if self.is_macro_rules_item() {
212 self.parse_item_macro_rules(vis)?
213 } else if vis.node.is_pub() && self.isnt_macro_invocation() {
214 self.recover_missing_kw_before_item()?;
216 } else if macros_allowed && self.token.is_path_start() {
217 // MACRO INVOCATION ITEM
218 (Ident::invalid(), ItemKind::Mac(self.parse_item_macro(vis)?))
225 /// When parsing a statement, would the start of a path be an item?
226 pub(super) fn is_path_start_item(&mut self) -> bool {
227 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
228 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
229 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
230 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
231 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
234 /// Are we sure this could not possibly be a macro invocation?
235 fn isnt_macro_invocation(&mut self) -> bool {
236 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
239 /// Recover on encountering a struct or method definition where the user
240 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
241 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
242 // Space between `pub` keyword and the identifier
245 // ^^^ `sp` points here
246 let sp = self.prev_span.between(self.token.span);
247 let full_sp = self.prev_span.to(self.token.span);
248 let ident_sp = self.token.span;
249 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
250 // possible public struct definition where `struct` was forgotten
251 let ident = self.parse_ident().unwrap();
252 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
253 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
254 err.span_suggestion_short(
258 Applicability::MaybeIncorrect, // speculative
261 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
262 let ident = self.parse_ident().unwrap();
264 let kw_name = self.recover_first_param();
265 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
266 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
267 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
269 ("fn", kw_name, false)
270 } else if self.check(&token::OpenDelim(token::Brace)) {
272 ("fn", kw_name, false)
273 } else if self.check(&token::Colon) {
277 ("fn` or `struct", "function or struct", true)
280 let msg = format!("missing `{}` for {} definition", kw, kw_name);
281 let mut err = self.struct_span_err(sp, &msg);
283 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
285 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
286 err.span_suggestion_short(
290 Applicability::MachineApplicable,
293 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
296 "if you meant to call a macro, try",
297 format!("{}!", snippet),
298 // this is the `ambiguous` conditional branch
299 Applicability::MaybeIncorrect,
303 "if you meant to call a macro, remove the `pub` \
304 and add a trailing `!` after the identifier",
309 } else if self.look_ahead(1, |t| *t == token::Lt) {
310 let ident = self.parse_ident().unwrap();
311 self.eat_to_tokens(&[&token::Gt]);
313 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
314 ("fn", self.recover_first_param(), false)
315 } else if self.check(&token::OpenDelim(token::Brace)) {
316 ("struct", "struct", false)
318 ("fn` or `struct", "function or struct", true)
320 let msg = format!("missing `{}` for {} definition", kw, kw_name);
321 let mut err = self.struct_span_err(sp, &msg);
323 err.span_suggestion_short(
325 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
327 Applicability::MachineApplicable,
336 /// Parses an item macro, e.g., `item!();`.
337 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, Mac> {
338 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
339 self.expect(&token::Not)?; // `!`
340 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
341 self.eat_semi_for_macro_if_needed(&args);
342 self.complain_if_pub_macro(vis, false);
343 Ok(Mac { path, args, prior_type_ascription: self.last_type_ascription })
346 /// Recover if we parsed attributes and expected an item but there was none.
347 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
348 let (start, end) = match attrs {
351 [x0, .., xn] => (x0, xn),
353 let msg = if end.is_doc_comment() {
354 "expected item after doc comment"
356 "expected item after attributes"
358 let mut err = self.struct_span_err(end.span, msg);
359 if end.is_doc_comment() {
360 err.span_label(end.span, "this doc comment doesn't document anything");
362 if let [.., penultimate, _] = attrs {
363 err.span_label(start.span.to(penultimate.span), "other attributes here");
368 fn is_async_fn(&self) -> bool {
369 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
372 /// Parses an implementation item.
375 /// impl<'a, T> TYPE { /* impl items */ }
376 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
377 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
378 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
381 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
383 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
384 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
388 attrs: &mut Vec<Attribute>,
389 defaultness: Defaultness,
390 ) -> PResult<'a, ItemInfo> {
391 let unsafety = self.parse_unsafety();
392 self.expect_keyword(kw::Impl)?;
394 // First, parse generic parameters if necessary.
395 let mut generics = if self.choose_generics_over_qpath() {
396 self.parse_generics()?
398 let mut generics = Generics::default();
400 // /\ this is where `generics.span` should point when there are no type params.
401 generics.span = self.prev_span.shrink_to_hi();
405 let constness = self.parse_constness();
406 if let Const::Yes(span) = constness {
407 self.sess.gated_spans.gate(sym::const_trait_impl, span);
410 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
411 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
413 ast::ImplPolarity::Negative
415 ast::ImplPolarity::Positive
418 // Parse both types and traits as a type, then reinterpret if necessary.
419 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
420 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
422 let span = self.prev_span.between(self.token.span);
423 self.struct_span_err(span, "missing trait in a trait impl").emit();
424 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
429 // If `for` is missing we try to recover.
430 let has_for = self.eat_keyword(kw::For);
431 let missing_for_span = self.prev_span.between(self.token.span);
433 let ty_second = if self.token == token::DotDot {
434 // We need to report this error after `cfg` expansion for compatibility reasons
435 self.bump(); // `..`, do not add it to expected tokens
436 Some(self.mk_ty(self.prev_span, TyKind::Err))
437 } else if has_for || self.token.can_begin_type() {
438 Some(self.parse_ty()?)
443 generics.where_clause = self.parse_where_clause()?;
445 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
447 let item_kind = match ty_second {
449 // impl Trait for Type
451 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
452 .span_suggestion_short(
456 Applicability::MachineApplicable,
461 let ty_first = ty_first.into_inner();
462 let path = match ty_first.kind {
463 // This notably includes paths passed through `ty` macro fragments (#46438).
464 TyKind::Path(None, path) => path,
466 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
467 err_path(ty_first.span)
470 let trait_ref = TraitRef { path, ref_id: ty_first.id };
478 of_trait: Some(trait_ref),
498 Ok((Ident::invalid(), item_kind))
501 fn parse_item_list<T>(
503 attrs: &mut Vec<Attribute>,
504 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
505 ) -> PResult<'a, Vec<T>> {
506 let open_brace_span = self.token.span;
507 self.expect(&token::OpenDelim(token::Brace))?;
508 attrs.append(&mut self.parse_inner_attributes()?);
510 let mut items = Vec::new();
511 while !self.eat(&token::CloseDelim(token::Brace)) {
512 if self.recover_doc_comment_before_brace() {
515 match parse_item(self) {
517 // We have to bail or we'll potentially never make progress.
518 let non_item_span = self.token.span;
519 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
520 self.struct_span_err(non_item_span, "non-item in item list")
521 .span_label(open_brace_span, "item list starts here")
522 .span_label(non_item_span, "non-item starts here")
523 .span_label(self.prev_span, "item list ends here")
527 Ok(Some(item)) => items.extend(item),
529 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
530 err.span_label(open_brace_span, "while parsing this item list starting here")
531 .span_label(self.prev_span, "the item list ends here")
540 /// Recover on a doc comment before `}`.
541 fn recover_doc_comment_before_brace(&mut self) -> bool {
542 if let token::DocComment(_) = self.token.kind {
543 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
548 "found a documentation comment that doesn't document anything",
550 .span_label(self.token.span, "this doc comment doesn't document anything")
552 "doc comments must come before what they document, maybe a \
553 comment was intended with `//`?",
563 /// Parses defaultness (i.e., `default` or nothing).
564 fn parse_defaultness(&mut self) -> Defaultness {
565 // We are interested in `default` followed by another identifier.
566 // However, we must avoid keywords that occur as binary operators.
567 // Currently, the only applicable keyword is `as` (`default as Ty`).
568 if self.check_keyword(kw::Default)
569 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
571 self.bump(); // `default`
572 Defaultness::Default(self.prev_span)
578 /// Is this an `(unsafe auto? | auto) trait` item?
579 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
581 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
583 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
586 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
587 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
588 let unsafety = self.parse_unsafety();
589 // Parse optional `auto` prefix.
590 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
592 self.expect_keyword(kw::Trait)?;
593 let ident = self.parse_ident()?;
594 let mut tps = self.parse_generics()?;
596 // Parse optional colon and supertrait bounds.
597 let had_colon = self.eat(&token::Colon);
598 let span_at_colon = self.prev_span;
600 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
602 let span_before_eq = self.prev_span;
603 if self.eat(&token::Eq) {
604 // It's a trait alias.
606 let span = span_at_colon.to(span_before_eq);
607 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
610 let bounds = self.parse_generic_bounds(None)?;
611 tps.where_clause = self.parse_where_clause()?;
614 let whole_span = lo.to(self.prev_span);
615 if is_auto == IsAuto::Yes {
616 let msg = "trait aliases cannot be `auto`";
617 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
619 if let Unsafe::Yes(_) = unsafety {
620 let msg = "trait aliases cannot be `unsafe`";
621 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
624 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
626 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
628 // It's a normal trait.
629 tps.where_clause = self.parse_where_clause()?;
630 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
631 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
635 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
636 self.parse_assoc_item(|_| true)
639 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
640 self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
643 /// Parses associated items.
644 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
645 Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
646 let kind = match kind {
647 ItemKind::Mac(a) => AssocItemKind::Macro(a),
648 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
649 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
650 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
651 ItemKind::Static(a, _, b) => {
652 self.struct_span_err(span, "associated `static` items are not allowed").emit();
653 AssocItemKind::Const(Defaultness::Final, a, b)
655 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
657 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
661 /// Parses a `type` alias with the following grammar:
663 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
665 /// The `"type"` has already been eaten.
666 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
667 let ident = self.parse_ident()?;
668 let mut generics = self.parse_generics()?;
670 // Parse optional colon and param bounds.
672 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
673 generics.where_clause = self.parse_where_clause()?;
675 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
678 Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
681 /// Parses a `UseTree`.
684 /// USE_TREE = [`::`] `*` |
685 /// [`::`] `{` USE_TREE_LIST `}` |
687 /// PATH `::` `{` USE_TREE_LIST `}` |
688 /// PATH [`as` IDENT]
690 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
691 let lo = self.token.span;
693 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
694 let kind = if self.check(&token::OpenDelim(token::Brace))
695 || self.check(&token::BinOp(token::Star))
696 || self.is_import_coupler()
698 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
699 let mod_sep_ctxt = self.token.span.ctxt();
700 if self.eat(&token::ModSep) {
703 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
706 self.parse_use_tree_glob_or_nested()?
708 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
709 prefix = self.parse_path(PathStyle::Mod)?;
711 if self.eat(&token::ModSep) {
712 self.parse_use_tree_glob_or_nested()?
714 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
718 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
721 /// Parses `*` or `{...}`.
722 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
723 Ok(if self.eat(&token::BinOp(token::Star)) {
726 UseTreeKind::Nested(self.parse_use_tree_list()?)
730 /// Parses a `UseTreeKind::Nested(list)`.
733 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
735 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
736 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
740 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
741 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
744 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
745 match self.normalized_token.kind {
746 token::Ident(name @ kw::Underscore, false) => {
748 Ok(Ident::new(name, self.normalized_prev_token.span))
750 _ => self.parse_ident(),
754 /// Parses `extern crate` links.
759 /// extern crate foo;
760 /// extern crate bar as foo;
762 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
763 // Accept `extern crate name-like-this` for better diagnostics
764 let orig_name = self.parse_crate_name_with_dashes()?;
765 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
766 (rename, Some(orig_name.name))
771 Ok((item_name, ItemKind::ExternCrate(orig_name)))
774 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
775 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
776 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
778 let mut ident = if self.token.is_keyword(kw::SelfLower) {
779 self.parse_path_segment_ident()
783 let mut idents = vec![];
784 let mut replacement = vec![];
785 let mut fixed_crate_name = false;
786 // Accept `extern crate name-like-this` for better diagnostics.
787 let dash = token::BinOp(token::BinOpToken::Minus);
788 if self.token == dash {
789 // Do not include `-` as part of the expected tokens list.
790 while self.eat(&dash) {
791 fixed_crate_name = true;
792 replacement.push((self.prev_span, "_".to_string()));
793 idents.push(self.parse_ident()?);
796 if fixed_crate_name {
797 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
798 let mut fixed_name = format!("{}", ident.name);
800 fixed_name.push_str(&format!("_{}", part.name));
802 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
804 self.struct_span_err(fixed_name_sp, error_msg)
805 .span_label(fixed_name_sp, "dash-separated idents are not valid")
806 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
812 /// Parses `extern` for foreign ABIs modules.
814 /// `extern` is expected to have been consumed before calling this method.
818 /// ```ignore (only-for-syntax-highlight)
822 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
823 let abi = self.parse_abi(); // ABI?
824 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
825 let module = ast::ForeignMod { abi, items };
826 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
829 /// Parses a foreign item (one in an `extern { ... }` block).
830 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
831 Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
832 let kind = match kind {
833 ItemKind::Mac(a) => ForeignItemKind::Macro(a),
834 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
835 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
836 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
837 ItemKind::Const(_, a, b) => {
838 self.error_on_foreign_const(span, ident);
839 ForeignItemKind::Static(a, Mutability::Not, b)
841 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
843 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
847 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
848 let span = self.sess.source_map().def_span(span);
849 let msg = format!("{} is not supported in {}", kind.descr(), ctx);
850 self.struct_span_err(span, &msg).emit();
854 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
855 self.struct_span_err(ident.span, "extern items cannot be `const`")
857 span.with_hi(ident.span.lo()),
858 "try using a static value",
859 "static ".to_string(),
860 Applicability::MachineApplicable,
862 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
866 fn is_static_global(&mut self) -> bool {
867 if self.check_keyword(kw::Static) {
868 // Check if this could be a closure.
869 !self.look_ahead(1, |token| {
870 if token.is_keyword(kw::Move) {
874 token::BinOp(token::Or) | token::OrOr => true,
883 /// Recover on `const mut` with `const` already eaten.
884 fn recover_const_mut(&mut self, const_span: Span) {
885 if self.eat_keyword(kw::Mut) {
886 let span = self.prev_span;
887 self.struct_span_err(span, "const globals cannot be mutable")
888 .span_label(span, "cannot be mutable")
891 "you might want to declare a static instead",
893 Applicability::MaybeIncorrect,
899 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
900 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
902 /// When `m` is `"const"`, `$ident` may also be `"_"`.
903 fn parse_item_global(
905 m: Option<Mutability>,
906 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
907 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
909 // Parse the type of a `const` or `static mut?` item.
910 // That is, the `":" $ty` fragment.
911 let ty = if self.eat(&token::Colon) {
914 self.recover_missing_const_type(id, m)
917 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
922 /// We were supposed to parse `:` but the `:` was missing.
923 /// This means that the type is missing.
924 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
925 // Construct the error and stash it away with the hope
926 // that typeck will later enrich the error with a type.
928 Some(Mutability::Mut) => "static mut",
929 Some(Mutability::Not) => "static",
932 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
935 "provide a type for the item",
936 format!("{}: <type>", id),
937 Applicability::HasPlaceholders,
939 err.stash(id.span, StashKey::ItemNoType);
941 // The user intended that the type be inferred,
942 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
943 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
946 /// Parses an enum declaration.
947 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
948 let id = self.parse_ident()?;
949 let mut generics = self.parse_generics()?;
950 generics.where_clause = self.parse_where_clause()?;
953 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
958 let enum_definition =
959 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
960 Ok((id, ItemKind::Enum(enum_definition, generics)))
963 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
964 let variant_attrs = self.parse_outer_attributes()?;
965 let vlo = self.token.span;
967 let vis = self.parse_visibility(FollowedByType::No)?;
968 if !self.recover_nested_adt_item(kw::Enum)? {
971 let ident = self.parse_ident()?;
973 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
974 // Parse a struct variant.
975 let (fields, recovered) = self.parse_record_struct_body()?;
976 VariantData::Struct(fields, recovered)
977 } else if self.check(&token::OpenDelim(token::Paren)) {
978 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
980 VariantData::Unit(DUMMY_NODE_ID)
984 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
986 let vr = ast::Variant {
990 attrs: variant_attrs,
993 span: vlo.to(self.prev_span),
994 is_placeholder: false,
1000 /// Parses `struct Foo { ... }`.
1001 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1002 let class_name = self.parse_ident()?;
1004 let mut generics = self.parse_generics()?;
1006 // There is a special case worth noting here, as reported in issue #17904.
1007 // If we are parsing a tuple struct it is the case that the where clause
1008 // should follow the field list. Like so:
1010 // struct Foo<T>(T) where T: Copy;
1012 // If we are parsing a normal record-style struct it is the case
1013 // that the where clause comes before the body, and after the generics.
1014 // So if we look ahead and see a brace or a where-clause we begin
1015 // parsing a record style struct.
1017 // Otherwise if we look ahead and see a paren we parse a tuple-style
1020 let vdata = if self.token.is_keyword(kw::Where) {
1021 generics.where_clause = self.parse_where_clause()?;
1022 if self.eat(&token::Semi) {
1023 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1024 VariantData::Unit(DUMMY_NODE_ID)
1026 // If we see: `struct Foo<T> where T: Copy { ... }`
1027 let (fields, recovered) = self.parse_record_struct_body()?;
1028 VariantData::Struct(fields, recovered)
1030 // No `where` so: `struct Foo<T>;`
1031 } else if self.eat(&token::Semi) {
1032 VariantData::Unit(DUMMY_NODE_ID)
1033 // Record-style struct definition
1034 } else if self.token == token::OpenDelim(token::Brace) {
1035 let (fields, recovered) = self.parse_record_struct_body()?;
1036 VariantData::Struct(fields, recovered)
1037 // Tuple-style struct definition with optional where-clause.
1038 } else if self.token == token::OpenDelim(token::Paren) {
1039 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1040 generics.where_clause = self.parse_where_clause()?;
1041 self.expect_semi()?;
1044 let token_str = super::token_descr(&self.token);
1046 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1049 let mut err = self.struct_span_err(self.token.span, msg);
1050 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1054 Ok((class_name, ItemKind::Struct(vdata, generics)))
1057 /// Parses `union Foo { ... }`.
1058 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1059 let class_name = self.parse_ident()?;
1061 let mut generics = self.parse_generics()?;
1063 let vdata = if self.token.is_keyword(kw::Where) {
1064 generics.where_clause = self.parse_where_clause()?;
1065 let (fields, recovered) = self.parse_record_struct_body()?;
1066 VariantData::Struct(fields, recovered)
1067 } else if self.token == token::OpenDelim(token::Brace) {
1068 let (fields, recovered) = self.parse_record_struct_body()?;
1069 VariantData::Struct(fields, recovered)
1071 let token_str = super::token_descr(&self.token);
1072 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1073 let mut err = self.struct_span_err(self.token.span, msg);
1074 err.span_label(self.token.span, "expected `where` or `{` after union name");
1078 Ok((class_name, ItemKind::Union(vdata, generics)))
1081 fn parse_record_struct_body(
1083 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1084 let mut fields = Vec::new();
1085 let mut recovered = false;
1086 if self.eat(&token::OpenDelim(token::Brace)) {
1087 while self.token != token::CloseDelim(token::Brace) {
1088 let field = self.parse_struct_decl_field().map_err(|e| {
1089 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1094 Ok(field) => fields.push(field),
1101 self.eat(&token::CloseDelim(token::Brace));
1103 let token_str = super::token_descr(&self.token);
1104 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1105 let mut err = self.struct_span_err(self.token.span, msg);
1106 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1110 Ok((fields, recovered))
1113 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1114 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1115 // Unit like structs are handled in parse_item_struct function
1116 self.parse_paren_comma_seq(|p| {
1117 let attrs = p.parse_outer_attributes()?;
1118 let lo = p.token.span;
1119 let vis = p.parse_visibility(FollowedByType::Yes)?;
1120 let ty = p.parse_ty()?;
1122 span: lo.to(ty.span),
1128 is_placeholder: false,
1134 /// Parses an element of a struct declaration.
1135 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1136 let attrs = self.parse_outer_attributes()?;
1137 let lo = self.token.span;
1138 let vis = self.parse_visibility(FollowedByType::No)?;
1139 self.parse_single_struct_field(lo, vis, attrs)
1142 /// Parses a structure field declaration.
1143 fn parse_single_struct_field(
1147 attrs: Vec<Attribute>,
1148 ) -> PResult<'a, StructField> {
1149 let mut seen_comma: bool = false;
1150 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1151 if self.token == token::Comma {
1154 match self.token.kind {
1158 token::CloseDelim(token::Brace) => {}
1159 token::DocComment(_) => {
1160 let previous_span = self.prev_span;
1161 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1162 self.bump(); // consume the doc comment
1163 let comma_after_doc_seen = self.eat(&token::Comma);
1164 // `seen_comma` is always false, because we are inside doc block
1165 // condition is here to make code more readable
1166 if !seen_comma && comma_after_doc_seen {
1169 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1173 let sp = self.sess.source_map().next_point(previous_span);
1174 err.span_suggestion(
1176 "missing comma here",
1178 Applicability::MachineApplicable,
1185 let sp = self.prev_span.shrink_to_hi();
1186 let mut err = self.struct_span_err(
1188 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1190 if self.token.is_ident() {
1191 // This is likely another field; emit the diagnostic and keep going
1192 err.span_suggestion(
1194 "try adding a comma",
1196 Applicability::MachineApplicable,
1207 /// Parses a structure field.
1208 fn parse_name_and_ty(
1212 attrs: Vec<Attribute>,
1213 ) -> PResult<'a, StructField> {
1214 let name = self.parse_ident()?;
1215 self.expect(&token::Colon)?;
1216 let ty = self.parse_ty()?;
1218 span: lo.to(self.prev_span),
1224 is_placeholder: false,
1228 /// Parses a declarative macro 2.0 definition.
1229 /// The `macro` keyword has already been parsed.
1231 /// MacBody = "{" TOKEN_STREAM "}" ;
1232 /// MacParams = "(" TOKEN_STREAM ")" ;
1233 /// DeclMac = "macro" Ident MacParams? MacBody ;
1235 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1236 let ident = self.parse_ident()?;
1237 let body = if self.check(&token::OpenDelim(token::Brace)) {
1238 self.parse_mac_args()? // `MacBody`
1239 } else if self.check(&token::OpenDelim(token::Paren)) {
1240 let params = self.parse_token_tree(); // `MacParams`
1241 let pspan = params.span();
1242 if !self.check(&token::OpenDelim(token::Brace)) {
1243 return self.unexpected();
1245 let body = self.parse_token_tree(); // `MacBody`
1246 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1247 let bspan = body.span();
1248 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1249 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1250 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1251 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1253 return self.unexpected();
1256 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1257 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1260 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1261 fn is_macro_rules_item(&mut self) -> bool {
1262 self.check_keyword(kw::MacroRules)
1263 && self.look_ahead(1, |t| *t == token::Not)
1264 && self.look_ahead(2, |t| t.is_ident())
1267 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1268 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1269 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1270 self.expect(&token::Not)?; // `!`
1272 let ident = self.parse_ident()?;
1273 let body = self.parse_mac_args()?;
1274 self.eat_semi_for_macro_if_needed(&body);
1275 self.complain_if_pub_macro(vis, true);
1277 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1280 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1281 /// If that's not the case, emit an error.
1282 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1283 if let VisibilityKind::Inherited = vis.node {
1287 let vstr = pprust::vis_to_string(vis);
1288 let vstr = vstr.trim_end();
1290 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1291 self.struct_span_err(vis.span, &msg)
1294 "try exporting the macro",
1295 "#[macro_export]".to_owned(),
1296 Applicability::MaybeIncorrect, // speculative
1300 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1303 "remove the visibility",
1305 Applicability::MachineApplicable,
1307 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1312 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1313 if args.need_semicolon() && !self.eat(&token::Semi) {
1314 self.report_invalid_macro_expansion_item(args);
1318 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1319 let span = args.span().expect("undelimited macro call");
1320 let mut err = self.struct_span_err(
1322 "macros that expand to items must be delimited with braces or followed by a semicolon",
1324 if self.unclosed_delims.is_empty() {
1325 let DelimSpan { open, close } = match args {
1326 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1327 MacArgs::Delimited(dspan, ..) => *dspan,
1329 err.multipart_suggestion(
1330 "change the delimiters to curly braces",
1331 vec![(open, "{".to_string()), (close, '}'.to_string())],
1332 Applicability::MaybeIncorrect,
1335 err.span_suggestion(
1337 "change the delimiters to curly braces",
1338 " { /* items */ }".to_string(),
1339 Applicability::HasPlaceholders,
1342 err.span_suggestion(
1343 span.shrink_to_hi(),
1346 Applicability::MaybeIncorrect,
1351 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1352 /// it is, we try to parse the item and report error about nested types.
1353 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1354 if (self.token.is_keyword(kw::Enum)
1355 || self.token.is_keyword(kw::Struct)
1356 || self.token.is_keyword(kw::Union))
1357 && self.look_ahead(1, |t| t.is_ident())
1359 let kw_token = self.token.clone();
1360 let kw_str = pprust::token_to_string(&kw_token);
1361 let item = self.parse_item()?;
1363 self.struct_span_err(
1365 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1369 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1371 Applicability::MaybeIncorrect,
1374 // We successfully parsed the item but we must inform the caller about nested problem.
1381 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1383 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1384 type ReqName = fn(Edition) -> bool;
1386 /// Parsing of functions and methods.
1387 impl<'a> Parser<'a> {
1388 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1391 attrs: &mut Vec<Attribute>,
1393 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1394 let header = self.parse_fn_front_matter()?; // `const ... fn`
1395 let ident = self.parse_ident()?; // `foo`
1396 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1397 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1398 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1399 let body = self.parse_fn_body(attrs)?; // `;` or `{ ... }`.
1400 Ok((ident, FnSig { header, decl }, generics, body))
1403 /// Parse the "body" of a function.
1404 /// This can either be `;` when there's no body,
1405 /// or e.g. a block when the function is a provided one.
1406 fn parse_fn_body(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, Option<P<Block>>> {
1407 let (inner_attrs, body) = match self.token.kind {
1412 token::OpenDelim(token::Brace) => {
1413 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1416 token::Interpolated(ref nt) => match **nt {
1417 token::NtBlock(..) => {
1418 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1421 _ => return self.expected_semi_or_open_brace(),
1423 _ => return self.expected_semi_or_open_brace(),
1425 attrs.extend(inner_attrs);
1429 /// Is the current token the start of an `FnHeader` / not a valid parse?
1430 fn check_fn_front_matter(&mut self) -> bool {
1431 // We use an over-approximation here.
1432 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1433 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1434 self.check_keyword(kw::Fn) // Definitely an `fn`.
1435 // `$qual fn` or `$qual $qual`:
1436 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1437 && self.look_ahead(1, |t| {
1438 // ...qualified and then `fn`, e.g. `const fn`.
1439 t.is_keyword(kw::Fn)
1440 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1441 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1444 || self.check_keyword(kw::Extern)
1445 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1446 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1449 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1450 /// up to and including the `fn` keyword. The formal grammar is:
1453 /// Extern = "extern" StringLit ;
1454 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1455 /// FnFrontMatter = FnQual? "fn" ;
1457 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1458 let constness = self.parse_constness();
1459 let asyncness = self.parse_asyncness();
1460 let unsafety = self.parse_unsafety();
1461 let ext = self.parse_extern()?;
1463 if let Async::Yes { span, .. } = asyncness {
1464 self.ban_async_in_2015(span);
1467 if !self.eat_keyword(kw::Fn) {
1468 // It is possible for `expect_one_of` to recover given the contents of
1469 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1470 // account for this.
1471 if !self.expect_one_of(&[], &[])? {
1476 Ok(FnHeader { constness, unsafety, asyncness, ext })
1479 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1480 fn ban_async_in_2015(&self, span: Span) {
1481 if span.rust_2015() {
1482 let diag = self.diagnostic();
1483 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1484 .note("to use `async fn`, switch to Rust 2018")
1485 .help("set `edition = \"2018\"` in `Cargo.toml`")
1486 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1491 /// Parses the parameter list and result type of a function declaration.
1492 pub(super) fn parse_fn_decl(
1495 ret_allow_plus: AllowPlus,
1496 ) -> PResult<'a, P<FnDecl>> {
1498 inputs: self.parse_fn_params(req_name)?,
1499 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1503 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1504 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1505 let mut first_param = true;
1506 // Parse the arguments, starting out with `self` being allowed...
1507 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1508 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1510 let lo = p.prev_span;
1511 // Skip every token until next possible arg or end.
1512 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1513 // Create a placeholder argument for proper arg count (issue #34264).
1514 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1516 // ...now that we've parsed the first argument, `self` is no longer allowed.
1517 first_param = false;
1520 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1521 self.deduplicate_recovered_params_names(&mut params);
1525 /// Parses a single function parameter.
1527 /// - `self` is syntactically allowed when `first_param` holds.
1528 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1529 let lo = self.token.span;
1530 let attrs = self.parse_outer_attributes()?;
1532 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1533 if let Some(mut param) = self.parse_self_param()? {
1534 param.attrs = attrs.into();
1535 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1538 let is_name_required = match self.token.kind {
1539 token::DotDotDot => false,
1540 _ => req_name(self.normalized_token.span.edition()),
1542 let (pat, ty) = if is_name_required || self.is_named_param() {
1543 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1545 let pat = self.parse_fn_param_pat()?;
1546 if let Err(mut err) = self.expect(&token::Colon) {
1547 return if let Some(ident) =
1548 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1551 Ok(dummy_arg(ident))
1557 self.eat_incorrect_doc_comment_for_param_type();
1558 (pat, self.parse_ty_for_param()?)
1560 debug!("parse_param_general ident_to_pat");
1561 let parser_snapshot_before_ty = self.clone();
1562 self.eat_incorrect_doc_comment_for_param_type();
1563 let mut ty = self.parse_ty_for_param();
1565 && self.token != token::Comma
1566 && self.token != token::CloseDelim(token::Paren)
1568 // This wasn't actually a type, but a pattern looking like a type,
1569 // so we are going to rollback and re-parse for recovery.
1570 ty = self.unexpected();
1574 let ident = Ident::new(kw::Invalid, self.prev_span);
1575 let bm = BindingMode::ByValue(Mutability::Not);
1576 let pat = self.mk_pat_ident(ty.span, bm, ident);
1579 // If this is a C-variadic argument and we hit an error, return the error.
1580 Err(err) if self.token == token::DotDotDot => return Err(err),
1581 // Recover from attempting to parse the argument as a type without pattern.
1584 mem::replace(self, parser_snapshot_before_ty);
1585 self.recover_arg_parse()?
1590 let span = lo.to(self.token.span);
1593 attrs: attrs.into(),
1594 id: ast::DUMMY_NODE_ID,
1595 is_placeholder: false,
1602 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1603 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1604 // Extract an identifier *after* having confirmed that the token is one.
1605 let expect_self_ident = |this: &mut Self| {
1606 match this.normalized_token.kind {
1607 // Preserve hygienic context.
1608 token::Ident(name, _) => {
1610 Ident::new(name, this.normalized_prev_token.span)
1612 _ => unreachable!(),
1615 // Is `self` `n` tokens ahead?
1616 let is_isolated_self = |this: &Self, n| {
1617 this.is_keyword_ahead(n, &[kw::SelfLower])
1618 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1620 // Is `mut self` `n` tokens ahead?
1621 let is_isolated_mut_self =
1622 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1623 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1624 let parse_self_possibly_typed = |this: &mut Self, m| {
1625 let eself_ident = expect_self_ident(this);
1626 let eself_hi = this.prev_span;
1627 let eself = if this.eat(&token::Colon) {
1628 SelfKind::Explicit(this.parse_ty()?, m)
1632 Ok((eself, eself_ident, eself_hi))
1634 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1635 let recover_self_ptr = |this: &mut Self| {
1636 let msg = "cannot pass `self` by raw pointer";
1637 let span = this.token.span;
1638 this.struct_span_err(span, msg).span_label(span, msg).emit();
1640 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1643 // Parse optional `self` parameter of a method.
1644 // Only a limited set of initial token sequences is considered `self` parameters; anything
1645 // else is parsed as a normal function parameter list, so some lookahead is required.
1646 let eself_lo = self.token.span;
1647 let (eself, eself_ident, eself_hi) = match self.normalized_token.kind {
1648 token::BinOp(token::And) => {
1649 let eself = if is_isolated_self(self, 1) {
1652 SelfKind::Region(None, Mutability::Not)
1653 } else if is_isolated_mut_self(self, 1) {
1657 SelfKind::Region(None, Mutability::Mut)
1658 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1661 let lt = self.expect_lifetime();
1662 SelfKind::Region(Some(lt), Mutability::Not)
1663 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1666 let lt = self.expect_lifetime();
1668 SelfKind::Region(Some(lt), Mutability::Mut)
1673 (eself, expect_self_ident(self), self.prev_span)
1676 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1678 recover_self_ptr(self)?
1680 // `*mut self` and `*const self`
1681 token::BinOp(token::Star)
1682 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1686 recover_self_ptr(self)?
1688 // `self` and `self: TYPE`
1689 token::Ident(..) if is_isolated_self(self, 0) => {
1690 parse_self_possibly_typed(self, Mutability::Not)?
1692 // `mut self` and `mut self: TYPE`
1693 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1695 parse_self_possibly_typed(self, Mutability::Mut)?
1697 _ => return Ok(None),
1700 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1701 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1704 fn is_named_param(&self) -> bool {
1705 let offset = match self.token.kind {
1706 token::Interpolated(ref nt) => match **nt {
1707 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1710 token::BinOp(token::And) | token::AndAnd => 1,
1711 _ if self.token.is_keyword(kw::Mut) => 1,
1715 self.look_ahead(offset, |t| t.is_ident())
1716 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1719 fn recover_first_param(&mut self) -> &'static str {
1721 .parse_outer_attributes()
1722 .and_then(|_| self.parse_self_param())
1723 .map_err(|mut e| e.cancel())
1725 Ok(Some(_)) => "method",