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};
10 Async, Const, Defaultness, IsAuto, PathSegment, Unsafe, UseTree, UseTreeKind,
13 BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind,
15 use rustc_ast::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
16 use rustc_ast::ast::{FnHeader, ForeignItem, Mutability, Visibility, VisibilityKind};
17 use rustc_ast::ptr::P;
19 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
20 use rustc_ast_pretty::pprust;
21 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
22 use rustc_span::source_map::{self, Span};
23 use rustc_span::symbol::{kw, sym, Symbol};
28 pub(super) type ItemInfo = (Ident, ItemKind);
31 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
32 self.parse_item_(|_| true).map(|i| i.map(P))
35 fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
36 let attrs = self.parse_outer_attributes()?;
37 self.parse_item_common(attrs, true, false, req_name)
40 pub(super) fn parse_item_common(
42 mut attrs: Vec<Attribute>,
46 ) -> PResult<'a, Option<Item>> {
47 maybe_whole!(self, NtItem, |item| {
49 mem::swap(&mut item.attrs, &mut attrs);
50 item.attrs.extend(attrs);
51 Some(item.into_inner())
54 let mut unclosed_delims = vec![];
55 let (mut item, tokens) = self.collect_tokens(|this| {
56 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
57 unclosed_delims.append(&mut this.unclosed_delims);
60 self.unclosed_delims.append(&mut unclosed_delims);
62 // Once we've parsed an item and recorded the tokens we got while
63 // parsing we may want to store `tokens` into the item we're about to
64 // return. Note, though, that we specifically didn't capture tokens
65 // related to outer attributes. The `tokens` field here may later be
66 // used with procedural macros to convert this item back into a token
67 // stream, but during expansion we may be removing attributes as we go
70 // If we've got inner attributes then the `tokens` we've got above holds
71 // these inner attributes. If an inner attribute is expanded we won't
72 // actually remove it from the token stream, so we'll just keep yielding
73 // it (bad!). To work around this case for now we just avoid recording
74 // `tokens` if we detect any inner attributes. This should help keep
75 // expansion correct, but we should fix this bug one day!
76 if let Some(item) = &mut item {
77 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
78 item.tokens = Some(tokens);
84 fn parse_item_common_(
86 mut attrs: Vec<Attribute>,
90 ) -> PResult<'a, Option<Item>> {
91 let lo = self.token.span;
92 let vis = self.parse_visibility(FollowedByType::No)?;
93 let mut def = self.parse_defaultness();
94 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
95 if let Some((ident, kind)) = kind {
96 self.error_on_unconsumed_default(def, &kind);
97 let span = lo.to(self.prev_span);
98 let id = DUMMY_NODE_ID;
99 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
100 return Ok(Some(item));
103 // At this point, we have failed to parse an item.
104 self.error_on_unmatched_vis(&vis);
105 self.error_on_unmatched_defaultness(def);
107 self.recover_attrs_no_item(&attrs)?;
112 /// Error in-case a non-inherited visibility was parsed but no item followed.
113 fn error_on_unmatched_vis(&self, vis: &Visibility) {
114 if let VisibilityKind::Inherited = vis.node {
117 let vs = pprust::vis_to_string(&vis);
118 let vs = vs.trim_end();
119 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
120 .span_label(vis.span, "the visibility")
121 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
125 /// Error in-case a `default` was parsed but no item followed.
126 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
127 if let Defaultness::Default(sp) = def {
128 self.struct_span_err(sp, "`default` is not followed by an item")
129 .span_label(sp, "the `default` qualifier")
130 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
135 /// Error in-case `default` was parsed in an in-appropriate context.
136 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
137 if let Defaultness::Default(span) = def {
138 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
139 self.struct_span_err(span, &msg)
140 .span_label(span, "`default` because of this")
141 .note("only associated `fn`, `const`, and `type` items can be `default`")
146 /// Parses one of the items allowed by the flags.
149 attrs: &mut Vec<Attribute>,
150 macros_allowed: bool,
153 def: &mut Defaultness,
155 ) -> PResult<'a, Option<ItemInfo>> {
156 let mut def = || mem::replace(def, Defaultness::Final);
158 let info = if self.eat_keyword(kw::Use) {
160 let tree = self.parse_use_tree()?;
162 (Ident::invalid(), ItemKind::Use(P(tree)))
163 } else if self.check_fn_front_matter() {
165 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name)?;
166 (ident, ItemKind::Fn(def(), sig, generics, body))
167 } else if self.eat_keyword(kw::Extern) {
168 if self.eat_keyword(kw::Crate) {
170 self.parse_item_extern_crate()?
173 self.parse_item_foreign_mod(attrs)?
175 } else if self.is_static_global() {
177 self.bump(); // `static`
178 let m = self.parse_mutability();
179 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
180 (ident, ItemKind::Static(ty, m, expr))
181 } else if let Const::Yes(const_span) = self.parse_constness() {
183 self.recover_const_mut(const_span);
184 let (ident, ty, expr) = self.parse_item_global(None)?;
185 (ident, ItemKind::Const(def(), ty, expr))
186 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
188 self.parse_item_trait(attrs, lo)?
189 } else if self.check_keyword(kw::Impl)
190 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
193 self.parse_item_impl(attrs, def())?
194 } else if self.eat_keyword(kw::Mod) {
196 self.parse_item_mod(attrs)?
197 } else if self.eat_keyword(kw::Type) {
199 self.parse_type_alias(def())?
200 } else if self.eat_keyword(kw::Enum) {
202 self.parse_item_enum()?
203 } else if self.eat_keyword(kw::Struct) {
205 self.parse_item_struct()?
206 } else if self.is_kw_followed_by_ident(kw::Union) {
208 self.bump(); // `union`
209 self.parse_item_union()?
210 } else if self.eat_keyword(kw::Macro) {
212 self.parse_item_decl_macro(lo)?
213 } else if self.is_macro_rules_item() {
215 self.parse_item_macro_rules(vis)?
216 } else if vis.node.is_pub() && self.isnt_macro_invocation() {
217 self.recover_missing_kw_before_item()?;
219 } else if macros_allowed && self.token.is_path_start() {
220 // MACRO INVOCATION ITEM
221 (Ident::invalid(), ItemKind::Mac(self.parse_item_macro(vis)?))
228 /// When parsing a statement, would the start of a path be an item?
229 pub(super) fn is_path_start_item(&mut self) -> bool {
230 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
231 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
232 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
233 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
234 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
237 /// Are we sure this could not possibly be a macro invocation?
238 fn isnt_macro_invocation(&mut self) -> bool {
239 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
242 /// Recover on encountering a struct or method definition where the user
243 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
244 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
245 // Space between `pub` keyword and the identifier
248 // ^^^ `sp` points here
249 let sp = self.prev_span.between(self.token.span);
250 let full_sp = self.prev_span.to(self.token.span);
251 let ident_sp = self.token.span;
252 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
253 // possible public struct definition where `struct` was forgotten
254 let ident = self.parse_ident().unwrap();
255 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
256 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
257 err.span_suggestion_short(
261 Applicability::MaybeIncorrect, // speculative
264 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
265 let ident = self.parse_ident().unwrap();
267 let kw_name = self.recover_first_param();
268 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
269 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
270 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
272 ("fn", kw_name, false)
273 } else if self.check(&token::OpenDelim(token::Brace)) {
275 ("fn", kw_name, false)
276 } else if self.check(&token::Colon) {
280 ("fn` or `struct", "function or struct", true)
283 let msg = format!("missing `{}` for {} definition", kw, kw_name);
284 let mut err = self.struct_span_err(sp, &msg);
286 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
288 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
289 err.span_suggestion_short(
293 Applicability::MachineApplicable,
296 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
299 "if you meant to call a macro, try",
300 format!("{}!", snippet),
301 // this is the `ambiguous` conditional branch
302 Applicability::MaybeIncorrect,
306 "if you meant to call a macro, remove the `pub` \
307 and add a trailing `!` after the identifier",
312 } else if self.look_ahead(1, |t| *t == token::Lt) {
313 let ident = self.parse_ident().unwrap();
314 self.eat_to_tokens(&[&token::Gt]);
316 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
317 ("fn", self.recover_first_param(), false)
318 } else if self.check(&token::OpenDelim(token::Brace)) {
319 ("struct", "struct", false)
321 ("fn` or `struct", "function or struct", true)
323 let msg = format!("missing `{}` for {} definition", kw, kw_name);
324 let mut err = self.struct_span_err(sp, &msg);
326 err.span_suggestion_short(
328 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
330 Applicability::MachineApplicable,
339 /// Parses an item macro, e.g., `item!();`.
340 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, Mac> {
341 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
342 self.expect(&token::Not)?; // `!`
343 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
344 self.eat_semi_for_macro_if_needed(&args);
345 self.complain_if_pub_macro(vis, false);
346 Ok(Mac { path, args, prior_type_ascription: self.last_type_ascription })
349 /// Recover if we parsed attributes and expected an item but there was none.
350 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
351 let (start, end) = match attrs {
354 [x0, .., xn] => (x0, xn),
356 let msg = if end.is_doc_comment() {
357 "expected item after doc comment"
359 "expected item after attributes"
361 let mut err = self.struct_span_err(end.span, msg);
362 if end.is_doc_comment() {
363 err.span_label(end.span, "this doc comment doesn't document anything");
365 if let [.., penultimate, _] = attrs {
366 err.span_label(start.span.to(penultimate.span), "other attributes here");
371 fn is_async_fn(&self) -> bool {
372 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
375 /// Parses an implementation item.
378 /// impl<'a, T> TYPE { /* impl items */ }
379 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
380 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
381 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
384 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
386 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
387 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
391 attrs: &mut Vec<Attribute>,
392 defaultness: Defaultness,
393 ) -> PResult<'a, ItemInfo> {
394 let unsafety = self.parse_unsafety();
395 self.expect_keyword(kw::Impl)?;
397 // First, parse generic parameters if necessary.
398 let mut generics = if self.choose_generics_over_qpath() {
399 self.parse_generics()?
401 let mut generics = Generics::default();
403 // /\ this is where `generics.span` should point when there are no type params.
404 generics.span = self.prev_span.shrink_to_hi();
408 let constness = self.parse_constness();
409 if let Const::Yes(span) = constness {
410 self.sess.gated_spans.gate(sym::const_trait_impl, span);
413 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
414 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
416 ast::ImplPolarity::Negative
418 ast::ImplPolarity::Positive
421 // Parse both types and traits as a type, then reinterpret if necessary.
422 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
423 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
425 let span = self.prev_span.between(self.token.span);
426 self.struct_span_err(span, "missing trait in a trait impl").emit();
427 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
432 // If `for` is missing we try to recover.
433 let has_for = self.eat_keyword(kw::For);
434 let missing_for_span = self.prev_span.between(self.token.span);
436 let ty_second = if self.token == token::DotDot {
437 // We need to report this error after `cfg` expansion for compatibility reasons
438 self.bump(); // `..`, do not add it to expected tokens
439 Some(self.mk_ty(self.prev_span, TyKind::Err))
440 } else if has_for || self.token.can_begin_type() {
441 Some(self.parse_ty()?)
446 generics.where_clause = self.parse_where_clause()?;
448 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
450 let item_kind = match ty_second {
452 // impl Trait for Type
454 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
455 .span_suggestion_short(
459 Applicability::MachineApplicable,
464 let ty_first = ty_first.into_inner();
465 let path = match ty_first.kind {
466 // This notably includes paths passed through `ty` macro fragments (#46438).
467 TyKind::Path(None, path) => path,
469 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
470 err_path(ty_first.span)
473 let trait_ref = TraitRef { path, ref_id: ty_first.id };
481 of_trait: Some(trait_ref),
501 Ok((Ident::invalid(), item_kind))
504 fn parse_item_list<T>(
506 attrs: &mut Vec<Attribute>,
507 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
508 ) -> PResult<'a, Vec<T>> {
509 let open_brace_span = self.token.span;
510 self.expect(&token::OpenDelim(token::Brace))?;
511 attrs.append(&mut self.parse_inner_attributes()?);
513 let mut items = Vec::new();
514 while !self.eat(&token::CloseDelim(token::Brace)) {
515 if self.recover_doc_comment_before_brace() {
518 match parse_item(self) {
520 // We have to bail or we'll potentially never make progress.
521 let non_item_span = self.token.span;
522 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
523 self.struct_span_err(non_item_span, "non-item in item list")
524 .span_label(open_brace_span, "item list starts here")
525 .span_label(non_item_span, "non-item starts here")
526 .span_label(self.prev_span, "item list ends here")
530 Ok(Some(item)) => items.extend(item),
532 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
533 err.span_label(open_brace_span, "while parsing this item list starting here")
534 .span_label(self.prev_span, "the item list ends here")
543 /// Recover on a doc comment before `}`.
544 fn recover_doc_comment_before_brace(&mut self) -> bool {
545 if let token::DocComment(_) = self.token.kind {
546 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
551 "found a documentation comment that doesn't document anything",
553 .span_label(self.token.span, "this doc comment doesn't document anything")
555 "doc comments must come before what they document, maybe a \
556 comment was intended with `//`?",
566 /// Parses defaultness (i.e., `default` or nothing).
567 fn parse_defaultness(&mut self) -> Defaultness {
568 // We are interested in `default` followed by another identifier.
569 // However, we must avoid keywords that occur as binary operators.
570 // Currently, the only applicable keyword is `as` (`default as Ty`).
571 if self.check_keyword(kw::Default)
572 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
574 self.bump(); // `default`
575 Defaultness::Default(self.prev_span)
581 /// Is this an `(unsafe auto? | auto) trait` item?
582 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
584 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
586 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
589 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
590 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
591 let unsafety = self.parse_unsafety();
592 // Parse optional `auto` prefix.
593 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
595 self.expect_keyword(kw::Trait)?;
596 let ident = self.parse_ident()?;
597 let mut tps = self.parse_generics()?;
599 // Parse optional colon and supertrait bounds.
600 let had_colon = self.eat(&token::Colon);
601 let span_at_colon = self.prev_span;
603 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
605 let span_before_eq = self.prev_span;
606 if self.eat(&token::Eq) {
607 // It's a trait alias.
609 let span = span_at_colon.to(span_before_eq);
610 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
613 let bounds = self.parse_generic_bounds(None)?;
614 tps.where_clause = self.parse_where_clause()?;
617 let whole_span = lo.to(self.prev_span);
618 if is_auto == IsAuto::Yes {
619 let msg = "trait aliases cannot be `auto`";
620 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
622 if let Unsafe::Yes(_) = unsafety {
623 let msg = "trait aliases cannot be `unsafe`";
624 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
627 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
629 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
631 // It's a normal trait.
632 tps.where_clause = self.parse_where_clause()?;
633 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
634 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
638 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
639 self.parse_assoc_item(|_| true)
642 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
643 self.parse_assoc_item(|t| t.span.rust_2018())
646 /// Parses associated items.
647 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
648 Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
649 let kind = match kind {
650 ItemKind::Mac(a) => AssocItemKind::Macro(a),
651 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
652 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
653 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
654 ItemKind::Static(a, _, b) => {
655 self.struct_span_err(span, "associated `static` items are not allowed").emit();
656 AssocItemKind::Const(Defaultness::Final, a, b)
658 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
660 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
664 /// Parses a `type` alias with the following grammar:
666 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
668 /// The `"type"` has already been eaten.
669 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
670 let ident = self.parse_ident()?;
671 let mut generics = self.parse_generics()?;
673 // Parse optional colon and param bounds.
675 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
676 generics.where_clause = self.parse_where_clause()?;
678 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
681 Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
684 /// Parses a `UseTree`.
687 /// USE_TREE = [`::`] `*` |
688 /// [`::`] `{` USE_TREE_LIST `}` |
690 /// PATH `::` `{` USE_TREE_LIST `}` |
691 /// PATH [`as` IDENT]
693 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
694 let lo = self.token.span;
696 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
697 let kind = if self.check(&token::OpenDelim(token::Brace))
698 || self.check(&token::BinOp(token::Star))
699 || self.is_import_coupler()
701 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
702 let mod_sep_ctxt = self.token.span.ctxt();
703 if self.eat(&token::ModSep) {
706 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
709 self.parse_use_tree_glob_or_nested()?
711 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
712 prefix = self.parse_path(PathStyle::Mod)?;
714 if self.eat(&token::ModSep) {
715 self.parse_use_tree_glob_or_nested()?
717 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
721 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
724 /// Parses `*` or `{...}`.
725 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
726 Ok(if self.eat(&token::BinOp(token::Star)) {
729 UseTreeKind::Nested(self.parse_use_tree_list()?)
733 /// Parses a `UseTreeKind::Nested(list)`.
736 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
738 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
739 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
743 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
744 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
747 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
748 match self.normalized_token.kind {
749 token::Ident(name @ kw::Underscore, false) => {
751 Ok(Ident::new(name, self.normalized_prev_token.span))
753 _ => self.parse_ident(),
757 /// Parses `extern crate` links.
762 /// extern crate foo;
763 /// extern crate bar as foo;
765 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
766 // Accept `extern crate name-like-this` for better diagnostics
767 let orig_name = self.parse_crate_name_with_dashes()?;
768 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
769 (rename, Some(orig_name.name))
774 Ok((item_name, ItemKind::ExternCrate(orig_name)))
777 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
778 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
779 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
781 let mut ident = if self.token.is_keyword(kw::SelfLower) {
782 self.parse_path_segment_ident()
786 let mut idents = vec![];
787 let mut replacement = vec![];
788 let mut fixed_crate_name = false;
789 // Accept `extern crate name-like-this` for better diagnostics.
790 let dash = token::BinOp(token::BinOpToken::Minus);
791 if self.token == dash {
792 // Do not include `-` as part of the expected tokens list.
793 while self.eat(&dash) {
794 fixed_crate_name = true;
795 replacement.push((self.prev_span, "_".to_string()));
796 idents.push(self.parse_ident()?);
799 if fixed_crate_name {
800 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
801 let mut fixed_name = format!("{}", ident.name);
803 fixed_name.push_str(&format!("_{}", part.name));
805 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
807 self.struct_span_err(fixed_name_sp, error_msg)
808 .span_label(fixed_name_sp, "dash-separated idents are not valid")
809 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
815 /// Parses `extern` for foreign ABIs modules.
817 /// `extern` is expected to have been consumed before calling this method.
821 /// ```ignore (only-for-syntax-highlight)
825 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
826 let abi = self.parse_abi(); // ABI?
827 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
828 let module = ast::ForeignMod { abi, items };
829 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
832 /// Parses a foreign item (one in an `extern { ... }` block).
833 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
834 Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
835 let kind = match kind {
836 ItemKind::Mac(a) => ForeignItemKind::Macro(a),
837 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
838 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
839 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
840 ItemKind::Const(_, a, b) => {
841 self.error_on_foreign_const(span, ident);
842 ForeignItemKind::Static(a, Mutability::Not, b)
844 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
846 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
850 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
851 let span = self.sess.source_map().def_span(span);
852 let msg = format!("{} is not supported in {}", kind.descr(), ctx);
853 self.struct_span_err(span, &msg).emit();
857 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
858 self.struct_span_err(ident.span, "extern items cannot be `const`")
860 span.with_hi(ident.span.lo()),
861 "try using a static value",
862 "static ".to_string(),
863 Applicability::MachineApplicable,
865 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
869 fn is_static_global(&mut self) -> bool {
870 if self.check_keyword(kw::Static) {
871 // Check if this could be a closure.
872 !self.look_ahead(1, |token| {
873 if token.is_keyword(kw::Move) {
877 token::BinOp(token::Or) | token::OrOr => true,
886 /// Recover on `const mut` with `const` already eaten.
887 fn recover_const_mut(&mut self, const_span: Span) {
888 if self.eat_keyword(kw::Mut) {
889 let span = self.prev_span;
890 self.struct_span_err(span, "const globals cannot be mutable")
891 .span_label(span, "cannot be mutable")
894 "you might want to declare a static instead",
896 Applicability::MaybeIncorrect,
902 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
903 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
905 /// When `m` is `"const"`, `$ident` may also be `"_"`.
906 fn parse_item_global(
908 m: Option<Mutability>,
909 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
910 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
912 // Parse the type of a `const` or `static mut?` item.
913 // That is, the `":" $ty` fragment.
914 let ty = if self.eat(&token::Colon) {
917 self.recover_missing_const_type(id, m)
920 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
925 /// We were supposed to parse `:` but the `:` was missing.
926 /// This means that the type is missing.
927 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
928 // Construct the error and stash it away with the hope
929 // that typeck will later enrich the error with a type.
931 Some(Mutability::Mut) => "static mut",
932 Some(Mutability::Not) => "static",
935 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
938 "provide a type for the item",
939 format!("{}: <type>", id),
940 Applicability::HasPlaceholders,
942 err.stash(id.span, StashKey::ItemNoType);
944 // The user intended that the type be inferred,
945 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
946 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
949 /// Parses an enum declaration.
950 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
951 let id = self.parse_ident()?;
952 let mut generics = self.parse_generics()?;
953 generics.where_clause = self.parse_where_clause()?;
956 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
961 let enum_definition =
962 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
963 Ok((id, ItemKind::Enum(enum_definition, generics)))
966 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
967 let variant_attrs = self.parse_outer_attributes()?;
968 let vlo = self.token.span;
970 let vis = self.parse_visibility(FollowedByType::No)?;
971 if !self.recover_nested_adt_item(kw::Enum)? {
974 let ident = self.parse_ident()?;
976 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
977 // Parse a struct variant.
978 let (fields, recovered) = self.parse_record_struct_body()?;
979 VariantData::Struct(fields, recovered)
980 } else if self.check(&token::OpenDelim(token::Paren)) {
981 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
983 VariantData::Unit(DUMMY_NODE_ID)
987 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
989 let vr = ast::Variant {
993 attrs: variant_attrs,
996 span: vlo.to(self.prev_span),
997 is_placeholder: false,
1003 /// Parses `struct Foo { ... }`.
1004 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1005 let class_name = self.parse_ident()?;
1007 let mut generics = self.parse_generics()?;
1009 // There is a special case worth noting here, as reported in issue #17904.
1010 // If we are parsing a tuple struct it is the case that the where clause
1011 // should follow the field list. Like so:
1013 // struct Foo<T>(T) where T: Copy;
1015 // If we are parsing a normal record-style struct it is the case
1016 // that the where clause comes before the body, and after the generics.
1017 // So if we look ahead and see a brace or a where-clause we begin
1018 // parsing a record style struct.
1020 // Otherwise if we look ahead and see a paren we parse a tuple-style
1023 let vdata = if self.token.is_keyword(kw::Where) {
1024 generics.where_clause = self.parse_where_clause()?;
1025 if self.eat(&token::Semi) {
1026 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1027 VariantData::Unit(DUMMY_NODE_ID)
1029 // If we see: `struct Foo<T> where T: Copy { ... }`
1030 let (fields, recovered) = self.parse_record_struct_body()?;
1031 VariantData::Struct(fields, recovered)
1033 // No `where` so: `struct Foo<T>;`
1034 } else if self.eat(&token::Semi) {
1035 VariantData::Unit(DUMMY_NODE_ID)
1036 // Record-style struct definition
1037 } else if self.token == token::OpenDelim(token::Brace) {
1038 let (fields, recovered) = self.parse_record_struct_body()?;
1039 VariantData::Struct(fields, recovered)
1040 // Tuple-style struct definition with optional where-clause.
1041 } else if self.token == token::OpenDelim(token::Paren) {
1042 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1043 generics.where_clause = self.parse_where_clause()?;
1044 self.expect_semi()?;
1047 let token_str = super::token_descr(&self.token);
1049 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1052 let mut err = self.struct_span_err(self.token.span, msg);
1053 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1057 Ok((class_name, ItemKind::Struct(vdata, generics)))
1060 /// Parses `union Foo { ... }`.
1061 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1062 let class_name = self.parse_ident()?;
1064 let mut generics = self.parse_generics()?;
1066 let vdata = if self.token.is_keyword(kw::Where) {
1067 generics.where_clause = self.parse_where_clause()?;
1068 let (fields, recovered) = self.parse_record_struct_body()?;
1069 VariantData::Struct(fields, recovered)
1070 } else if self.token == token::OpenDelim(token::Brace) {
1071 let (fields, recovered) = self.parse_record_struct_body()?;
1072 VariantData::Struct(fields, recovered)
1074 let token_str = super::token_descr(&self.token);
1075 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1076 let mut err = self.struct_span_err(self.token.span, msg);
1077 err.span_label(self.token.span, "expected `where` or `{` after union name");
1081 Ok((class_name, ItemKind::Union(vdata, generics)))
1084 fn parse_record_struct_body(
1086 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1087 let mut fields = Vec::new();
1088 let mut recovered = false;
1089 if self.eat(&token::OpenDelim(token::Brace)) {
1090 while self.token != token::CloseDelim(token::Brace) {
1091 let field = self.parse_struct_decl_field().map_err(|e| {
1092 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1097 Ok(field) => fields.push(field),
1104 self.eat(&token::CloseDelim(token::Brace));
1106 let token_str = super::token_descr(&self.token);
1107 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1108 let mut err = self.struct_span_err(self.token.span, msg);
1109 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1113 Ok((fields, recovered))
1116 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1117 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1118 // Unit like structs are handled in parse_item_struct function
1119 self.parse_paren_comma_seq(|p| {
1120 let attrs = p.parse_outer_attributes()?;
1121 let lo = p.token.span;
1122 let vis = p.parse_visibility(FollowedByType::Yes)?;
1123 let ty = p.parse_ty()?;
1125 span: lo.to(ty.span),
1131 is_placeholder: false,
1137 /// Parses an element of a struct declaration.
1138 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1139 let attrs = self.parse_outer_attributes()?;
1140 let lo = self.token.span;
1141 let vis = self.parse_visibility(FollowedByType::No)?;
1142 self.parse_single_struct_field(lo, vis, attrs)
1145 /// Parses a structure field declaration.
1146 fn parse_single_struct_field(
1150 attrs: Vec<Attribute>,
1151 ) -> PResult<'a, StructField> {
1152 let mut seen_comma: bool = false;
1153 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1154 if self.token == token::Comma {
1157 match self.token.kind {
1161 token::CloseDelim(token::Brace) => {}
1162 token::DocComment(_) => {
1163 let previous_span = self.prev_span;
1164 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1165 self.bump(); // consume the doc comment
1166 let comma_after_doc_seen = self.eat(&token::Comma);
1167 // `seen_comma` is always false, because we are inside doc block
1168 // condition is here to make code more readable
1169 if !seen_comma && comma_after_doc_seen {
1172 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1176 let sp = self.sess.source_map().next_point(previous_span);
1177 err.span_suggestion(
1179 "missing comma here",
1181 Applicability::MachineApplicable,
1188 let sp = self.prev_span.shrink_to_hi();
1189 let mut err = self.struct_span_err(
1191 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1193 if self.token.is_ident() {
1194 // This is likely another field; emit the diagnostic and keep going
1195 err.span_suggestion(
1197 "try adding a comma",
1199 Applicability::MachineApplicable,
1210 /// Parses a structure field.
1211 fn parse_name_and_ty(
1215 attrs: Vec<Attribute>,
1216 ) -> PResult<'a, StructField> {
1217 let name = self.parse_ident()?;
1218 self.expect(&token::Colon)?;
1219 let ty = self.parse_ty()?;
1221 span: lo.to(self.prev_span),
1227 is_placeholder: false,
1231 /// Parses a declarative macro 2.0 definition.
1232 /// The `macro` keyword has already been parsed.
1234 /// MacBody = "{" TOKEN_STREAM "}" ;
1235 /// MacParams = "(" TOKEN_STREAM ")" ;
1236 /// DeclMac = "macro" Ident MacParams? MacBody ;
1238 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1239 let ident = self.parse_ident()?;
1240 let body = if self.check(&token::OpenDelim(token::Brace)) {
1241 self.parse_mac_args()? // `MacBody`
1242 } else if self.check(&token::OpenDelim(token::Paren)) {
1243 let params = self.parse_token_tree(); // `MacParams`
1244 let pspan = params.span();
1245 if !self.check(&token::OpenDelim(token::Brace)) {
1246 return self.unexpected();
1248 let body = self.parse_token_tree(); // `MacBody`
1249 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1250 let bspan = body.span();
1251 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1252 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1253 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1254 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1256 return self.unexpected();
1259 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1260 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1263 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1264 fn is_macro_rules_item(&mut self) -> bool {
1265 self.check_keyword(kw::MacroRules)
1266 && self.look_ahead(1, |t| *t == token::Not)
1267 && self.look_ahead(2, |t| t.is_ident())
1270 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1271 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1272 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1273 self.expect(&token::Not)?; // `!`
1275 let ident = self.parse_ident()?;
1276 let body = self.parse_mac_args()?;
1277 self.eat_semi_for_macro_if_needed(&body);
1278 self.complain_if_pub_macro(vis, true);
1280 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1283 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1284 /// If that's not the case, emit an error.
1285 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1286 if let VisibilityKind::Inherited = vis.node {
1290 let vstr = pprust::vis_to_string(vis);
1291 let vstr = vstr.trim_end();
1293 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1294 self.struct_span_err(vis.span, &msg)
1297 "try exporting the macro",
1298 "#[macro_export]".to_owned(),
1299 Applicability::MaybeIncorrect, // speculative
1303 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1306 "remove the visibility",
1308 Applicability::MachineApplicable,
1310 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1315 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1316 if args.need_semicolon() && !self.eat(&token::Semi) {
1317 self.report_invalid_macro_expansion_item(args);
1321 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1322 let span = args.span().expect("undelimited macro call");
1323 let mut err = self.struct_span_err(
1325 "macros that expand to items must be delimited with braces or followed by a semicolon",
1327 if self.unclosed_delims.is_empty() {
1328 let DelimSpan { open, close } = match args {
1329 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1330 MacArgs::Delimited(dspan, ..) => *dspan,
1332 err.multipart_suggestion(
1333 "change the delimiters to curly braces",
1334 vec![(open, "{".to_string()), (close, '}'.to_string())],
1335 Applicability::MaybeIncorrect,
1338 err.span_suggestion(
1340 "change the delimiters to curly braces",
1341 " { /* items */ }".to_string(),
1342 Applicability::HasPlaceholders,
1345 err.span_suggestion(
1346 span.shrink_to_hi(),
1349 Applicability::MaybeIncorrect,
1354 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1355 /// it is, we try to parse the item and report error about nested types.
1356 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1357 if (self.token.is_keyword(kw::Enum)
1358 || self.token.is_keyword(kw::Struct)
1359 || self.token.is_keyword(kw::Union))
1360 && self.look_ahead(1, |t| t.is_ident())
1362 let kw_token = self.token.clone();
1363 let kw_str = pprust::token_to_string(&kw_token);
1364 let item = self.parse_item()?;
1366 self.struct_span_err(
1368 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1372 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1374 Applicability::MaybeIncorrect,
1377 // We successfully parsed the item but we must inform the caller about nested problem.
1384 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1386 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1387 type ReqName = fn(&token::Token) -> bool;
1389 /// Parsing of functions and methods.
1390 impl<'a> Parser<'a> {
1391 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1394 attrs: &mut Vec<Attribute>,
1396 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1397 let header = self.parse_fn_front_matter()?; // `const ... fn`
1398 let ident = self.parse_ident()?; // `foo`
1399 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1400 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1401 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1402 let body = self.parse_fn_body(attrs)?; // `;` or `{ ... }`.
1403 Ok((ident, FnSig { header, decl }, generics, body))
1406 /// Parse the "body" of a function.
1407 /// This can either be `;` when there's no body,
1408 /// or e.g. a block when the function is a provided one.
1409 fn parse_fn_body(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, Option<P<Block>>> {
1410 let (inner_attrs, body) = match self.token.kind {
1415 token::OpenDelim(token::Brace) => {
1416 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1419 token::Interpolated(ref nt) => match **nt {
1420 token::NtBlock(..) => {
1421 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1424 _ => return self.expected_semi_or_open_brace(),
1426 _ => return self.expected_semi_or_open_brace(),
1428 attrs.extend(inner_attrs);
1432 /// Is the current token the start of an `FnHeader` / not a valid parse?
1433 fn check_fn_front_matter(&mut self) -> bool {
1434 // We use an over-approximation here.
1435 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1436 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1437 self.check_keyword(kw::Fn) // Definitely an `fn`.
1438 // `$qual fn` or `$qual $qual`:
1439 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1440 && self.look_ahead(1, |t| {
1441 // ...qualified and then `fn`, e.g. `const fn`.
1442 t.is_keyword(kw::Fn)
1443 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1444 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1447 || self.check_keyword(kw::Extern)
1448 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1449 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1452 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1453 /// up to and including the `fn` keyword. The formal grammar is:
1456 /// Extern = "extern" StringLit ;
1457 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1458 /// FnFrontMatter = FnQual? "fn" ;
1460 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1461 let constness = self.parse_constness();
1462 let asyncness = self.parse_asyncness();
1463 let unsafety = self.parse_unsafety();
1464 let ext = self.parse_extern()?;
1466 if let Async::Yes { span, .. } = asyncness {
1467 self.ban_async_in_2015(span);
1470 if !self.eat_keyword(kw::Fn) {
1471 // It is possible for `expect_one_of` to recover given the contents of
1472 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1473 // account for this.
1474 if !self.expect_one_of(&[], &[])? {
1479 Ok(FnHeader { constness, unsafety, asyncness, ext })
1482 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1483 fn ban_async_in_2015(&self, span: Span) {
1484 if span.rust_2015() {
1485 let diag = self.diagnostic();
1486 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1487 .note("to use `async fn`, switch to Rust 2018")
1488 .help("set `edition = \"2018\"` in `Cargo.toml`")
1489 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1494 /// Parses the parameter list and result type of a function declaration.
1495 pub(super) fn parse_fn_decl(
1498 ret_allow_plus: AllowPlus,
1499 ) -> PResult<'a, P<FnDecl>> {
1501 inputs: self.parse_fn_params(req_name)?,
1502 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1506 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1507 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1508 let mut first_param = true;
1509 // Parse the arguments, starting out with `self` being allowed...
1510 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1511 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1513 let lo = p.prev_span;
1514 // Skip every token until next possible arg or end.
1515 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1516 // Create a placeholder argument for proper arg count (issue #34264).
1517 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1519 // ...now that we've parsed the first argument, `self` is no longer allowed.
1520 first_param = false;
1523 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1524 self.deduplicate_recovered_params_names(&mut params);
1528 /// Parses a single function parameter.
1530 /// - `self` is syntactically allowed when `first_param` holds.
1531 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1532 let lo = self.token.span;
1533 let attrs = self.parse_outer_attributes()?;
1535 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1536 if let Some(mut param) = self.parse_self_param()? {
1537 param.attrs = attrs.into();
1538 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1541 let is_name_required = match self.token.kind {
1542 token::DotDotDot => false,
1543 _ => req_name(&self.normalized_token),
1545 let (pat, ty) = if is_name_required || self.is_named_param() {
1546 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1548 let pat = self.parse_fn_param_pat()?;
1549 if let Err(mut err) = self.expect(&token::Colon) {
1550 return if let Some(ident) =
1551 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1554 Ok(dummy_arg(ident))
1560 self.eat_incorrect_doc_comment_for_param_type();
1561 (pat, self.parse_ty_for_param()?)
1563 debug!("parse_param_general ident_to_pat");
1564 let parser_snapshot_before_ty = self.clone();
1565 self.eat_incorrect_doc_comment_for_param_type();
1566 let mut ty = self.parse_ty_for_param();
1568 && self.token != token::Comma
1569 && self.token != token::CloseDelim(token::Paren)
1571 // This wasn't actually a type, but a pattern looking like a type,
1572 // so we are going to rollback and re-parse for recovery.
1573 ty = self.unexpected();
1577 let ident = Ident::new(kw::Invalid, self.prev_span);
1578 let bm = BindingMode::ByValue(Mutability::Not);
1579 let pat = self.mk_pat_ident(ty.span, bm, ident);
1582 // If this is a C-variadic argument and we hit an error, return the error.
1583 Err(err) if self.token == token::DotDotDot => return Err(err),
1584 // Recover from attempting to parse the argument as a type without pattern.
1587 mem::replace(self, parser_snapshot_before_ty);
1588 self.recover_arg_parse()?
1593 let span = lo.to(self.token.span);
1596 attrs: attrs.into(),
1597 id: ast::DUMMY_NODE_ID,
1598 is_placeholder: false,
1605 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1606 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1607 // Extract an identifier *after* having confirmed that the token is one.
1608 let expect_self_ident = |this: &mut Self| {
1609 match this.normalized_token.kind {
1610 // Preserve hygienic context.
1611 token::Ident(name, _) => {
1613 Ident::new(name, this.normalized_prev_token.span)
1615 _ => unreachable!(),
1618 // Is `self` `n` tokens ahead?
1619 let is_isolated_self = |this: &Self, n| {
1620 this.is_keyword_ahead(n, &[kw::SelfLower])
1621 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1623 // Is `mut self` `n` tokens ahead?
1624 let is_isolated_mut_self =
1625 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1626 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1627 let parse_self_possibly_typed = |this: &mut Self, m| {
1628 let eself_ident = expect_self_ident(this);
1629 let eself_hi = this.prev_span;
1630 let eself = if this.eat(&token::Colon) {
1631 SelfKind::Explicit(this.parse_ty()?, m)
1635 Ok((eself, eself_ident, eself_hi))
1637 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1638 let recover_self_ptr = |this: &mut Self| {
1639 let msg = "cannot pass `self` by raw pointer";
1640 let span = this.token.span;
1641 this.struct_span_err(span, msg).span_label(span, msg).emit();
1643 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1646 // Parse optional `self` parameter of a method.
1647 // Only a limited set of initial token sequences is considered `self` parameters; anything
1648 // else is parsed as a normal function parameter list, so some lookahead is required.
1649 let eself_lo = self.token.span;
1650 let (eself, eself_ident, eself_hi) = match self.normalized_token.kind {
1651 token::BinOp(token::And) => {
1652 let eself = if is_isolated_self(self, 1) {
1655 SelfKind::Region(None, Mutability::Not)
1656 } else if is_isolated_mut_self(self, 1) {
1660 SelfKind::Region(None, Mutability::Mut)
1661 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1664 let lt = self.expect_lifetime();
1665 SelfKind::Region(Some(lt), Mutability::Not)
1666 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1669 let lt = self.expect_lifetime();
1671 SelfKind::Region(Some(lt), Mutability::Mut)
1676 (eself, expect_self_ident(self), self.prev_span)
1679 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1681 recover_self_ptr(self)?
1683 // `*mut self` and `*const self`
1684 token::BinOp(token::Star)
1685 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1689 recover_self_ptr(self)?
1691 // `self` and `self: TYPE`
1692 token::Ident(..) if is_isolated_self(self, 0) => {
1693 parse_self_possibly_typed(self, Mutability::Not)?
1695 // `mut self` and `mut self: TYPE`
1696 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1698 parse_self_possibly_typed(self, Mutability::Mut)?
1700 _ => return Ok(None),
1703 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1704 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1707 fn is_named_param(&self) -> bool {
1708 let offset = match self.token.kind {
1709 token::Interpolated(ref nt) => match **nt {
1710 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1713 token::BinOp(token::And) | token::AndAnd => 1,
1714 _ if self.token.is_keyword(kw::Mut) => 1,
1718 self.look_ahead(offset, |t| t.is_ident())
1719 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1722 fn recover_first_param(&mut self) -> &'static str {
1724 .parse_outer_attributes()
1725 .and_then(|_| self.parse_self_param())
1726 .map_err(|mut e| e.cancel())
1728 Ok(Some(_)) => "method",