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::edition::Edition;
23 use rustc_span::source_map::{self, Span};
24 use rustc_span::symbol::{kw, sym, Symbol};
29 pub(super) type ItemInfo = (Ident, ItemKind);
32 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
33 self.parse_item_(|_| true).map(|i| i.map(P))
36 fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
37 let attrs = self.parse_outer_attributes()?;
38 self.parse_item_common(attrs, true, false, req_name)
41 pub(super) fn parse_item_common(
43 mut attrs: Vec<Attribute>,
47 ) -> PResult<'a, Option<Item>> {
48 maybe_whole!(self, NtItem, |item| {
50 mem::swap(&mut item.attrs, &mut attrs);
51 item.attrs.extend(attrs);
52 Some(item.into_inner())
55 let mut unclosed_delims = vec![];
56 let (mut item, tokens) = self.collect_tokens(|this| {
57 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
58 unclosed_delims.append(&mut this.unclosed_delims);
61 self.unclosed_delims.append(&mut unclosed_delims);
63 // Once we've parsed an item and recorded the tokens we got while
64 // parsing we may want to store `tokens` into the item we're about to
65 // return. Note, though, that we specifically didn't capture tokens
66 // related to outer attributes. The `tokens` field here may later be
67 // used with procedural macros to convert this item back into a token
68 // stream, but during expansion we may be removing attributes as we go
71 // If we've got inner attributes then the `tokens` we've got above holds
72 // these inner attributes. If an inner attribute is expanded we won't
73 // actually remove it from the token stream, so we'll just keep yielding
74 // it (bad!). To work around this case for now we just avoid recording
75 // `tokens` if we detect any inner attributes. This should help keep
76 // expansion correct, but we should fix this bug one day!
77 if let Some(item) = &mut item {
78 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
79 item.tokens = Some(tokens);
85 fn parse_item_common_(
87 mut attrs: Vec<Attribute>,
91 ) -> PResult<'a, Option<Item>> {
92 let lo = self.token.span;
93 let vis = self.parse_visibility(FollowedByType::No)?;
94 let mut def = self.parse_defaultness();
95 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
96 if let Some((ident, kind)) = kind {
97 self.error_on_unconsumed_default(def, &kind);
98 let span = lo.to(self.prev_token.span);
99 let id = DUMMY_NODE_ID;
100 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
101 return Ok(Some(item));
104 // At this point, we have failed to parse an item.
105 self.error_on_unmatched_vis(&vis);
106 self.error_on_unmatched_defaultness(def);
108 self.recover_attrs_no_item(&attrs)?;
113 /// Error in-case a non-inherited visibility was parsed but no item followed.
114 fn error_on_unmatched_vis(&self, vis: &Visibility) {
115 if let VisibilityKind::Inherited = vis.node {
118 let vs = pprust::vis_to_string(&vis);
119 let vs = vs.trim_end();
120 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
121 .span_label(vis.span, "the visibility")
122 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
126 /// Error in-case a `default` was parsed but no item followed.
127 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
128 if let Defaultness::Default(sp) = def {
129 self.struct_span_err(sp, "`default` is not followed by an item")
130 .span_label(sp, "the `default` qualifier")
131 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
136 /// Error in-case `default` was parsed in an in-appropriate context.
137 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
138 if let Defaultness::Default(span) = def {
139 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
140 self.struct_span_err(span, &msg)
141 .span_label(span, "`default` because of this")
142 .note("only associated `fn`, `const`, and `type` items can be `default`")
147 /// Parses one of the items allowed by the flags.
150 attrs: &mut Vec<Attribute>,
151 macros_allowed: bool,
154 def: &mut Defaultness,
156 ) -> PResult<'a, Option<ItemInfo>> {
157 let mut def = || mem::replace(def, Defaultness::Final);
159 let info = if self.eat_keyword(kw::Use) {
161 let tree = self.parse_use_tree()?;
163 (Ident::invalid(), ItemKind::Use(P(tree)))
164 } else if self.check_fn_front_matter() {
166 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name)?;
167 (ident, ItemKind::Fn(def(), sig, generics, body))
168 } else if self.eat_keyword(kw::Extern) {
169 if self.eat_keyword(kw::Crate) {
171 self.parse_item_extern_crate()?
174 self.parse_item_foreign_mod(attrs)?
176 } else if self.is_static_global() {
178 self.bump(); // `static`
179 let m = self.parse_mutability();
180 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
181 (ident, ItemKind::Static(ty, m, expr))
182 } else if let Const::Yes(const_span) = self.parse_constness() {
184 self.recover_const_mut(const_span);
185 let (ident, ty, expr) = self.parse_item_global(None)?;
186 (ident, ItemKind::Const(def(), ty, expr))
187 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
189 self.parse_item_trait(attrs, lo)?
190 } else if self.check_keyword(kw::Impl)
191 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
194 self.parse_item_impl(attrs, def())?
195 } else if self.eat_keyword(kw::Mod) {
197 self.parse_item_mod(attrs)?
198 } else if self.eat_keyword(kw::Type) {
200 self.parse_type_alias(def())?
201 } else if self.eat_keyword(kw::Enum) {
203 self.parse_item_enum()?
204 } else if self.eat_keyword(kw::Struct) {
206 self.parse_item_struct()?
207 } else if self.is_kw_followed_by_ident(kw::Union) {
209 self.bump(); // `union`
210 self.parse_item_union()?
211 } else if self.eat_keyword(kw::Macro) {
213 self.parse_item_decl_macro(lo)?
214 } else if self.is_macro_rules_item() {
216 self.parse_item_macro_rules(vis)?
217 } else if vis.node.is_pub() && self.isnt_macro_invocation() {
218 self.recover_missing_kw_before_item()?;
220 } else if macros_allowed && self.token.is_path_start() {
221 // MACRO INVOCATION ITEM
222 (Ident::invalid(), ItemKind::Mac(self.parse_item_macro(vis)?))
229 /// When parsing a statement, would the start of a path be an item?
230 pub(super) fn is_path_start_item(&mut self) -> bool {
231 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
232 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
233 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
234 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
235 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
238 /// Are we sure this could not possibly be a macro invocation?
239 fn isnt_macro_invocation(&mut self) -> bool {
240 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
243 /// Recover on encountering a struct or method definition where the user
244 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
245 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
246 // Space between `pub` keyword and the identifier
249 // ^^^ `sp` points here
250 let sp = self.prev_token.span.between(self.token.span);
251 let full_sp = self.prev_token.span.to(self.token.span);
252 let ident_sp = self.token.span;
253 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
254 // possible public struct definition where `struct` was forgotten
255 let ident = self.parse_ident().unwrap();
256 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
257 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
258 err.span_suggestion_short(
262 Applicability::MaybeIncorrect, // speculative
265 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
266 let ident = self.parse_ident().unwrap();
268 let kw_name = self.recover_first_param();
269 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
270 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
271 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
273 ("fn", kw_name, false)
274 } else if self.check(&token::OpenDelim(token::Brace)) {
276 ("fn", kw_name, false)
277 } else if self.check(&token::Colon) {
281 ("fn` or `struct", "function or struct", true)
284 let msg = format!("missing `{}` for {} definition", kw, kw_name);
285 let mut err = self.struct_span_err(sp, &msg);
287 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
289 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
290 err.span_suggestion_short(
294 Applicability::MachineApplicable,
297 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
300 "if you meant to call a macro, try",
301 format!("{}!", snippet),
302 // this is the `ambiguous` conditional branch
303 Applicability::MaybeIncorrect,
307 "if you meant to call a macro, remove the `pub` \
308 and add a trailing `!` after the identifier",
313 } else if self.look_ahead(1, |t| *t == token::Lt) {
314 let ident = self.parse_ident().unwrap();
315 self.eat_to_tokens(&[&token::Gt]);
317 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
318 ("fn", self.recover_first_param(), false)
319 } else if self.check(&token::OpenDelim(token::Brace)) {
320 ("struct", "struct", false)
322 ("fn` or `struct", "function or struct", true)
324 let msg = format!("missing `{}` for {} definition", kw, kw_name);
325 let mut err = self.struct_span_err(sp, &msg);
327 err.span_suggestion_short(
329 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
331 Applicability::MachineApplicable,
340 /// Parses an item macro, e.g., `item!();`.
341 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, Mac> {
342 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
343 self.expect(&token::Not)?; // `!`
344 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
345 self.eat_semi_for_macro_if_needed(&args);
346 self.complain_if_pub_macro(vis, false);
347 Ok(Mac { path, args, prior_type_ascription: self.last_type_ascription })
350 /// Recover if we parsed attributes and expected an item but there was none.
351 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
352 let (start, end) = match attrs {
355 [x0, .., xn] => (x0, xn),
357 let msg = if end.is_doc_comment() {
358 "expected item after doc comment"
360 "expected item after attributes"
362 let mut err = self.struct_span_err(end.span, msg);
363 if end.is_doc_comment() {
364 err.span_label(end.span, "this doc comment doesn't document anything");
366 if let [.., penultimate, _] = attrs {
367 err.span_label(start.span.to(penultimate.span), "other attributes here");
372 fn is_async_fn(&self) -> bool {
373 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
376 /// Parses an implementation item.
379 /// impl<'a, T> TYPE { /* impl items */ }
380 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
381 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
382 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
385 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
387 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
388 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
392 attrs: &mut Vec<Attribute>,
393 defaultness: Defaultness,
394 ) -> PResult<'a, ItemInfo> {
395 let unsafety = self.parse_unsafety();
396 self.expect_keyword(kw::Impl)?;
398 // First, parse generic parameters if necessary.
399 let mut generics = if self.choose_generics_over_qpath() {
400 self.parse_generics()?
402 let mut generics = Generics::default();
404 // /\ this is where `generics.span` should point when there are no type params.
405 generics.span = self.prev_token.span.shrink_to_hi();
409 let constness = self.parse_constness();
410 if let Const::Yes(span) = constness {
411 self.sess.gated_spans.gate(sym::const_trait_impl, span);
414 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
415 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
417 ast::ImplPolarity::Negative
419 ast::ImplPolarity::Positive
422 // Parse both types and traits as a type, then reinterpret if necessary.
423 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
424 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
426 let span = self.prev_token.span.between(self.token.span);
427 self.struct_span_err(span, "missing trait in a trait impl").emit();
428 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
433 // If `for` is missing we try to recover.
434 let has_for = self.eat_keyword(kw::For);
435 let missing_for_span = self.prev_token.span.between(self.token.span);
437 let ty_second = if self.token == token::DotDot {
438 // We need to report this error after `cfg` expansion for compatibility reasons
439 self.bump(); // `..`, do not add it to expected tokens
440 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
441 } else if has_for || self.token.can_begin_type() {
442 Some(self.parse_ty()?)
447 generics.where_clause = self.parse_where_clause()?;
449 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
451 let item_kind = match ty_second {
453 // impl Trait for Type
455 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
456 .span_suggestion_short(
460 Applicability::MachineApplicable,
465 let ty_first = ty_first.into_inner();
466 let path = match ty_first.kind {
467 // This notably includes paths passed through `ty` macro fragments (#46438).
468 TyKind::Path(None, path) => path,
470 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
471 err_path(ty_first.span)
474 let trait_ref = TraitRef { path, ref_id: ty_first.id };
482 of_trait: Some(trait_ref),
502 Ok((Ident::invalid(), item_kind))
505 fn parse_item_list<T>(
507 attrs: &mut Vec<Attribute>,
508 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
509 ) -> PResult<'a, Vec<T>> {
510 let open_brace_span = self.token.span;
511 self.expect(&token::OpenDelim(token::Brace))?;
512 attrs.append(&mut self.parse_inner_attributes()?);
514 let mut items = Vec::new();
515 while !self.eat(&token::CloseDelim(token::Brace)) {
516 if self.recover_doc_comment_before_brace() {
519 match parse_item(self) {
521 // We have to bail or we'll potentially never make progress.
522 let non_item_span = self.token.span;
523 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
524 self.struct_span_err(non_item_span, "non-item in item list")
525 .span_label(open_brace_span, "item list starts here")
526 .span_label(non_item_span, "non-item starts here")
527 .span_label(self.prev_token.span, "item list ends here")
531 Ok(Some(item)) => items.extend(item),
533 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
534 err.span_label(open_brace_span, "while parsing this item list starting here")
535 .span_label(self.prev_token.span, "the item list ends here")
544 /// Recover on a doc comment before `}`.
545 fn recover_doc_comment_before_brace(&mut self) -> bool {
546 if let token::DocComment(_) = self.token.kind {
547 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
552 "found a documentation comment that doesn't document anything",
554 .span_label(self.token.span, "this doc comment doesn't document anything")
556 "doc comments must come before what they document, maybe a \
557 comment was intended with `//`?",
567 /// Parses defaultness (i.e., `default` or nothing).
568 fn parse_defaultness(&mut self) -> Defaultness {
569 // We are interested in `default` followed by another identifier.
570 // However, we must avoid keywords that occur as binary operators.
571 // Currently, the only applicable keyword is `as` (`default as Ty`).
572 if self.check_keyword(kw::Default)
573 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
575 self.bump(); // `default`
576 Defaultness::Default(self.normalized_prev_token.span)
582 /// Is this an `(unsafe auto? | auto) trait` item?
583 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
585 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
587 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
590 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
591 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
592 let unsafety = self.parse_unsafety();
593 // Parse optional `auto` prefix.
594 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
596 self.expect_keyword(kw::Trait)?;
597 let ident = self.parse_ident()?;
598 let mut tps = self.parse_generics()?;
600 // Parse optional colon and supertrait bounds.
601 let had_colon = self.eat(&token::Colon);
602 let span_at_colon = self.prev_token.span;
603 let bounds = if had_colon {
604 self.parse_generic_bounds(Some(self.prev_token.span))?
609 let span_before_eq = self.prev_token.span;
610 if self.eat(&token::Eq) {
611 // It's a trait alias.
613 let span = span_at_colon.to(span_before_eq);
614 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
617 let bounds = self.parse_generic_bounds(None)?;
618 tps.where_clause = self.parse_where_clause()?;
621 let whole_span = lo.to(self.prev_token.span);
622 if is_auto == IsAuto::Yes {
623 let msg = "trait aliases cannot be `auto`";
624 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
626 if let Unsafe::Yes(_) = unsafety {
627 let msg = "trait aliases cannot be `unsafe`";
628 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
631 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
633 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
635 // It's a normal trait.
636 tps.where_clause = self.parse_where_clause()?;
637 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
638 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
642 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
643 self.parse_assoc_item(|_| true)
646 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
647 self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
650 /// Parses associated items.
651 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
652 Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
653 let kind = match kind {
654 ItemKind::Mac(a) => AssocItemKind::Macro(a),
655 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
656 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
657 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
658 ItemKind::Static(a, _, b) => {
659 self.struct_span_err(span, "associated `static` items are not allowed").emit();
660 AssocItemKind::Const(Defaultness::Final, a, b)
662 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
664 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
668 /// Parses a `type` alias with the following grammar:
670 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
672 /// The `"type"` has already been eaten.
673 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
674 let ident = self.parse_ident()?;
675 let mut generics = self.parse_generics()?;
677 // Parse optional colon and param bounds.
679 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
680 generics.where_clause = self.parse_where_clause()?;
682 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
685 Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
688 /// Parses a `UseTree`.
691 /// USE_TREE = [`::`] `*` |
692 /// [`::`] `{` USE_TREE_LIST `}` |
694 /// PATH `::` `{` USE_TREE_LIST `}` |
695 /// PATH [`as` IDENT]
697 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
698 let lo = self.token.span;
700 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
701 let kind = if self.check(&token::OpenDelim(token::Brace))
702 || self.check(&token::BinOp(token::Star))
703 || self.is_import_coupler()
705 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
706 let mod_sep_ctxt = self.token.span.ctxt();
707 if self.eat(&token::ModSep) {
710 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
713 self.parse_use_tree_glob_or_nested()?
715 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
716 prefix = self.parse_path(PathStyle::Mod)?;
718 if self.eat(&token::ModSep) {
719 self.parse_use_tree_glob_or_nested()?
721 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
725 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
728 /// Parses `*` or `{...}`.
729 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
730 Ok(if self.eat(&token::BinOp(token::Star)) {
733 UseTreeKind::Nested(self.parse_use_tree_list()?)
737 /// Parses a `UseTreeKind::Nested(list)`.
740 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
742 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
743 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
747 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
748 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
751 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
752 match self.normalized_token.kind {
753 token::Ident(name @ kw::Underscore, false) => {
755 Ok(Ident::new(name, self.normalized_prev_token.span))
757 _ => self.parse_ident(),
761 /// Parses `extern crate` links.
766 /// extern crate foo;
767 /// extern crate bar as foo;
769 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
770 // Accept `extern crate name-like-this` for better diagnostics
771 let orig_name = self.parse_crate_name_with_dashes()?;
772 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
773 (rename, Some(orig_name.name))
778 Ok((item_name, ItemKind::ExternCrate(orig_name)))
781 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
782 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
783 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
785 let mut ident = if self.token.is_keyword(kw::SelfLower) {
786 self.parse_path_segment_ident()
790 let mut idents = vec![];
791 let mut replacement = vec![];
792 let mut fixed_crate_name = false;
793 // Accept `extern crate name-like-this` for better diagnostics.
794 let dash = token::BinOp(token::BinOpToken::Minus);
795 if self.token == dash {
796 // Do not include `-` as part of the expected tokens list.
797 while self.eat(&dash) {
798 fixed_crate_name = true;
799 replacement.push((self.prev_token.span, "_".to_string()));
800 idents.push(self.parse_ident()?);
803 if fixed_crate_name {
804 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
805 let mut fixed_name = format!("{}", ident.name);
807 fixed_name.push_str(&format!("_{}", part.name));
809 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
811 self.struct_span_err(fixed_name_sp, error_msg)
812 .span_label(fixed_name_sp, "dash-separated idents are not valid")
813 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
819 /// Parses `extern` for foreign ABIs modules.
821 /// `extern` is expected to have been consumed before calling this method.
825 /// ```ignore (only-for-syntax-highlight)
829 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
830 let abi = self.parse_abi(); // ABI?
831 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
832 let module = ast::ForeignMod { abi, items };
833 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
836 /// Parses a foreign item (one in an `extern { ... }` block).
837 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
838 Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
839 let kind = match kind {
840 ItemKind::Mac(a) => ForeignItemKind::Macro(a),
841 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
842 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
843 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
844 ItemKind::Const(_, a, b) => {
845 self.error_on_foreign_const(span, ident);
846 ForeignItemKind::Static(a, Mutability::Not, b)
848 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
850 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
854 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
855 let span = self.sess.source_map().def_span(span);
856 let msg = format!("{} is not supported in {}", kind.descr(), ctx);
857 self.struct_span_err(span, &msg).emit();
861 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
862 self.struct_span_err(ident.span, "extern items cannot be `const`")
864 span.with_hi(ident.span.lo()),
865 "try using a static value",
866 "static ".to_string(),
867 Applicability::MachineApplicable,
869 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
873 fn is_static_global(&mut self) -> bool {
874 if self.check_keyword(kw::Static) {
875 // Check if this could be a closure.
876 !self.look_ahead(1, |token| {
877 if token.is_keyword(kw::Move) {
881 token::BinOp(token::Or) | token::OrOr => true,
890 /// Recover on `const mut` with `const` already eaten.
891 fn recover_const_mut(&mut self, const_span: Span) {
892 if self.eat_keyword(kw::Mut) {
893 let span = self.prev_token.span;
894 self.struct_span_err(span, "const globals cannot be mutable")
895 .span_label(span, "cannot be mutable")
898 "you might want to declare a static instead",
900 Applicability::MaybeIncorrect,
906 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
907 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
909 /// When `m` is `"const"`, `$ident` may also be `"_"`.
910 fn parse_item_global(
912 m: Option<Mutability>,
913 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
914 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
916 // Parse the type of a `const` or `static mut?` item.
917 // That is, the `":" $ty` fragment.
918 let ty = if self.eat(&token::Colon) {
921 self.recover_missing_const_type(id, m)
924 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
929 /// We were supposed to parse `:` but the `:` was missing.
930 /// This means that the type is missing.
931 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
932 // Construct the error and stash it away with the hope
933 // that typeck will later enrich the error with a type.
935 Some(Mutability::Mut) => "static mut",
936 Some(Mutability::Not) => "static",
939 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
942 "provide a type for the item",
943 format!("{}: <type>", id),
944 Applicability::HasPlaceholders,
946 err.stash(id.span, StashKey::ItemNoType);
948 // The user intended that the type be inferred,
949 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
950 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
953 /// Parses an enum declaration.
954 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
955 let id = self.parse_ident()?;
956 let mut generics = self.parse_generics()?;
957 generics.where_clause = self.parse_where_clause()?;
960 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
965 let enum_definition =
966 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
967 Ok((id, ItemKind::Enum(enum_definition, generics)))
970 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
971 let variant_attrs = self.parse_outer_attributes()?;
972 let vlo = self.token.span;
974 let vis = self.parse_visibility(FollowedByType::No)?;
975 if !self.recover_nested_adt_item(kw::Enum)? {
978 let ident = self.parse_ident()?;
980 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
981 // Parse a struct variant.
982 let (fields, recovered) = self.parse_record_struct_body()?;
983 VariantData::Struct(fields, recovered)
984 } else if self.check(&token::OpenDelim(token::Paren)) {
985 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
987 VariantData::Unit(DUMMY_NODE_ID)
991 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
993 let vr = ast::Variant {
997 attrs: variant_attrs,
1000 span: vlo.to(self.prev_token.span),
1001 is_placeholder: false,
1007 /// Parses `struct Foo { ... }`.
1008 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1009 let class_name = self.parse_ident()?;
1011 let mut generics = self.parse_generics()?;
1013 // There is a special case worth noting here, as reported in issue #17904.
1014 // If we are parsing a tuple struct it is the case that the where clause
1015 // should follow the field list. Like so:
1017 // struct Foo<T>(T) where T: Copy;
1019 // If we are parsing a normal record-style struct it is the case
1020 // that the where clause comes before the body, and after the generics.
1021 // So if we look ahead and see a brace or a where-clause we begin
1022 // parsing a record style struct.
1024 // Otherwise if we look ahead and see a paren we parse a tuple-style
1027 let vdata = if self.token.is_keyword(kw::Where) {
1028 generics.where_clause = self.parse_where_clause()?;
1029 if self.eat(&token::Semi) {
1030 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1031 VariantData::Unit(DUMMY_NODE_ID)
1033 // If we see: `struct Foo<T> where T: Copy { ... }`
1034 let (fields, recovered) = self.parse_record_struct_body()?;
1035 VariantData::Struct(fields, recovered)
1037 // No `where` so: `struct Foo<T>;`
1038 } else if self.eat(&token::Semi) {
1039 VariantData::Unit(DUMMY_NODE_ID)
1040 // Record-style struct definition
1041 } else if self.token == token::OpenDelim(token::Brace) {
1042 let (fields, recovered) = self.parse_record_struct_body()?;
1043 VariantData::Struct(fields, recovered)
1044 // Tuple-style struct definition with optional where-clause.
1045 } else if self.token == token::OpenDelim(token::Paren) {
1046 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1047 generics.where_clause = self.parse_where_clause()?;
1048 self.expect_semi()?;
1051 let token_str = super::token_descr(&self.token);
1053 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1056 let mut err = self.struct_span_err(self.token.span, msg);
1057 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1061 Ok((class_name, ItemKind::Struct(vdata, generics)))
1064 /// Parses `union Foo { ... }`.
1065 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1066 let class_name = self.parse_ident()?;
1068 let mut generics = self.parse_generics()?;
1070 let vdata = if self.token.is_keyword(kw::Where) {
1071 generics.where_clause = self.parse_where_clause()?;
1072 let (fields, recovered) = self.parse_record_struct_body()?;
1073 VariantData::Struct(fields, recovered)
1074 } else if self.token == token::OpenDelim(token::Brace) {
1075 let (fields, recovered) = self.parse_record_struct_body()?;
1076 VariantData::Struct(fields, recovered)
1078 let token_str = super::token_descr(&self.token);
1079 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1080 let mut err = self.struct_span_err(self.token.span, msg);
1081 err.span_label(self.token.span, "expected `where` or `{` after union name");
1085 Ok((class_name, ItemKind::Union(vdata, generics)))
1088 fn parse_record_struct_body(
1090 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1091 let mut fields = Vec::new();
1092 let mut recovered = false;
1093 if self.eat(&token::OpenDelim(token::Brace)) {
1094 while self.token != token::CloseDelim(token::Brace) {
1095 let field = self.parse_struct_decl_field().map_err(|e| {
1096 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1101 Ok(field) => fields.push(field),
1108 self.eat(&token::CloseDelim(token::Brace));
1110 let token_str = super::token_descr(&self.token);
1111 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1112 let mut err = self.struct_span_err(self.token.span, msg);
1113 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1117 Ok((fields, recovered))
1120 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1121 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1122 // Unit like structs are handled in parse_item_struct function
1123 self.parse_paren_comma_seq(|p| {
1124 let attrs = p.parse_outer_attributes()?;
1125 let lo = p.token.span;
1126 let vis = p.parse_visibility(FollowedByType::Yes)?;
1127 let ty = p.parse_ty()?;
1129 span: lo.to(ty.span),
1135 is_placeholder: false,
1141 /// Parses an element of a struct declaration.
1142 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1143 let attrs = self.parse_outer_attributes()?;
1144 let lo = self.token.span;
1145 let vis = self.parse_visibility(FollowedByType::No)?;
1146 self.parse_single_struct_field(lo, vis, attrs)
1149 /// Parses a structure field declaration.
1150 fn parse_single_struct_field(
1154 attrs: Vec<Attribute>,
1155 ) -> PResult<'a, StructField> {
1156 let mut seen_comma: bool = false;
1157 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1158 if self.token == token::Comma {
1161 match self.token.kind {
1165 token::CloseDelim(token::Brace) => {}
1166 token::DocComment(_) => {
1167 let previous_span = self.prev_token.span;
1168 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1169 self.bump(); // consume the doc comment
1170 let comma_after_doc_seen = self.eat(&token::Comma);
1171 // `seen_comma` is always false, because we are inside doc block
1172 // condition is here to make code more readable
1173 if !seen_comma && comma_after_doc_seen {
1176 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1180 let sp = self.sess.source_map().next_point(previous_span);
1181 err.span_suggestion(
1183 "missing comma here",
1185 Applicability::MachineApplicable,
1192 let sp = self.prev_token.span.shrink_to_hi();
1193 let mut err = self.struct_span_err(
1195 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1197 if self.token.is_ident() {
1198 // This is likely another field; emit the diagnostic and keep going
1199 err.span_suggestion(
1201 "try adding a comma",
1203 Applicability::MachineApplicable,
1214 /// Parses a structure field.
1215 fn parse_name_and_ty(
1219 attrs: Vec<Attribute>,
1220 ) -> PResult<'a, StructField> {
1221 let name = self.parse_ident()?;
1222 self.expect(&token::Colon)?;
1223 let ty = self.parse_ty()?;
1225 span: lo.to(self.prev_token.span),
1231 is_placeholder: false,
1235 /// Parses a declarative macro 2.0 definition.
1236 /// The `macro` keyword has already been parsed.
1238 /// MacBody = "{" TOKEN_STREAM "}" ;
1239 /// MacParams = "(" TOKEN_STREAM ")" ;
1240 /// DeclMac = "macro" Ident MacParams? MacBody ;
1242 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1243 let ident = self.parse_ident()?;
1244 let body = if self.check(&token::OpenDelim(token::Brace)) {
1245 self.parse_mac_args()? // `MacBody`
1246 } else if self.check(&token::OpenDelim(token::Paren)) {
1247 let params = self.parse_token_tree(); // `MacParams`
1248 let pspan = params.span();
1249 if !self.check(&token::OpenDelim(token::Brace)) {
1250 return self.unexpected();
1252 let body = self.parse_token_tree(); // `MacBody`
1253 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1254 let bspan = body.span();
1255 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1256 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1257 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1258 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1260 return self.unexpected();
1263 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1264 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1267 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1268 fn is_macro_rules_item(&mut self) -> bool {
1269 self.check_keyword(kw::MacroRules)
1270 && self.look_ahead(1, |t| *t == token::Not)
1271 && self.look_ahead(2, |t| t.is_ident())
1274 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1275 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1276 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1277 self.expect(&token::Not)?; // `!`
1279 let ident = self.parse_ident()?;
1280 let body = self.parse_mac_args()?;
1281 self.eat_semi_for_macro_if_needed(&body);
1282 self.complain_if_pub_macro(vis, true);
1284 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1287 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1288 /// If that's not the case, emit an error.
1289 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1290 if let VisibilityKind::Inherited = vis.node {
1294 let vstr = pprust::vis_to_string(vis);
1295 let vstr = vstr.trim_end();
1297 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1298 self.struct_span_err(vis.span, &msg)
1301 "try exporting the macro",
1302 "#[macro_export]".to_owned(),
1303 Applicability::MaybeIncorrect, // speculative
1307 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1310 "remove the visibility",
1312 Applicability::MachineApplicable,
1314 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1319 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1320 if args.need_semicolon() && !self.eat(&token::Semi) {
1321 self.report_invalid_macro_expansion_item(args);
1325 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1326 let span = args.span().expect("undelimited macro call");
1327 let mut err = self.struct_span_err(
1329 "macros that expand to items must be delimited with braces or followed by a semicolon",
1331 if self.unclosed_delims.is_empty() {
1332 let DelimSpan { open, close } = match args {
1333 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1334 MacArgs::Delimited(dspan, ..) => *dspan,
1336 err.multipart_suggestion(
1337 "change the delimiters to curly braces",
1338 vec![(open, "{".to_string()), (close, '}'.to_string())],
1339 Applicability::MaybeIncorrect,
1342 err.span_suggestion(
1344 "change the delimiters to curly braces",
1345 " { /* items */ }".to_string(),
1346 Applicability::HasPlaceholders,
1349 err.span_suggestion(
1350 span.shrink_to_hi(),
1353 Applicability::MaybeIncorrect,
1358 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1359 /// it is, we try to parse the item and report error about nested types.
1360 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1361 if (self.token.is_keyword(kw::Enum)
1362 || self.token.is_keyword(kw::Struct)
1363 || self.token.is_keyword(kw::Union))
1364 && self.look_ahead(1, |t| t.is_ident())
1366 let kw_token = self.token.clone();
1367 let kw_str = pprust::token_to_string(&kw_token);
1368 let item = self.parse_item()?;
1370 self.struct_span_err(
1372 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1376 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1378 Applicability::MaybeIncorrect,
1381 // We successfully parsed the item but we must inform the caller about nested problem.
1388 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1390 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1391 type ReqName = fn(Edition) -> bool;
1393 /// Parsing of functions and methods.
1394 impl<'a> Parser<'a> {
1395 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1398 attrs: &mut Vec<Attribute>,
1400 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1401 let header = self.parse_fn_front_matter()?; // `const ... fn`
1402 let ident = self.parse_ident()?; // `foo`
1403 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1404 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1405 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1406 let body = self.parse_fn_body(attrs)?; // `;` or `{ ... }`.
1407 Ok((ident, FnSig { header, decl }, generics, body))
1410 /// Parse the "body" of a function.
1411 /// This can either be `;` when there's no body,
1412 /// or e.g. a block when the function is a provided one.
1413 fn parse_fn_body(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, Option<P<Block>>> {
1414 let (inner_attrs, body) = match self.token.kind {
1419 token::OpenDelim(token::Brace) => {
1420 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1423 token::Interpolated(ref nt) => match **nt {
1424 token::NtBlock(..) => {
1425 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1428 _ => return self.expected_semi_or_open_brace(),
1430 _ => return self.expected_semi_or_open_brace(),
1432 attrs.extend(inner_attrs);
1436 /// Is the current token the start of an `FnHeader` / not a valid parse?
1437 fn check_fn_front_matter(&mut self) -> bool {
1438 // We use an over-approximation here.
1439 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1440 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1441 self.check_keyword(kw::Fn) // Definitely an `fn`.
1442 // `$qual fn` or `$qual $qual`:
1443 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1444 && self.look_ahead(1, |t| {
1445 // ...qualified and then `fn`, e.g. `const fn`.
1446 t.is_keyword(kw::Fn)
1447 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1448 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1451 || self.check_keyword(kw::Extern)
1452 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1453 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1456 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1457 /// up to and including the `fn` keyword. The formal grammar is:
1460 /// Extern = "extern" StringLit ;
1461 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1462 /// FnFrontMatter = FnQual? "fn" ;
1464 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1465 let constness = self.parse_constness();
1466 let asyncness = self.parse_asyncness();
1467 let unsafety = self.parse_unsafety();
1468 let ext = self.parse_extern()?;
1470 if let Async::Yes { span, .. } = asyncness {
1471 self.ban_async_in_2015(span);
1474 if !self.eat_keyword(kw::Fn) {
1475 // It is possible for `expect_one_of` to recover given the contents of
1476 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1477 // account for this.
1478 if !self.expect_one_of(&[], &[])? {
1483 Ok(FnHeader { constness, unsafety, asyncness, ext })
1486 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1487 fn ban_async_in_2015(&self, span: Span) {
1488 if span.rust_2015() {
1489 let diag = self.diagnostic();
1490 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1491 .note("to use `async fn`, switch to Rust 2018")
1492 .help("set `edition = \"2018\"` in `Cargo.toml`")
1493 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1498 /// Parses the parameter list and result type of a function declaration.
1499 pub(super) fn parse_fn_decl(
1502 ret_allow_plus: AllowPlus,
1503 ) -> PResult<'a, P<FnDecl>> {
1505 inputs: self.parse_fn_params(req_name)?,
1506 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1510 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1511 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1512 let mut first_param = true;
1513 // Parse the arguments, starting out with `self` being allowed...
1514 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1515 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1517 let lo = p.prev_token.span;
1518 // Skip every token until next possible arg or end.
1519 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1520 // Create a placeholder argument for proper arg count (issue #34264).
1521 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_token.span))))
1523 // ...now that we've parsed the first argument, `self` is no longer allowed.
1524 first_param = false;
1527 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1528 self.deduplicate_recovered_params_names(&mut params);
1532 /// Parses a single function parameter.
1534 /// - `self` is syntactically allowed when `first_param` holds.
1535 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1536 let lo = self.token.span;
1537 let attrs = self.parse_outer_attributes()?;
1539 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1540 if let Some(mut param) = self.parse_self_param()? {
1541 param.attrs = attrs.into();
1542 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1545 let is_name_required = match self.token.kind {
1546 token::DotDotDot => false,
1547 _ => req_name(self.normalized_token.span.edition()),
1549 let (pat, ty) = if is_name_required || self.is_named_param() {
1550 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1552 let pat = self.parse_fn_param_pat()?;
1553 if let Err(mut err) = self.expect(&token::Colon) {
1554 return if let Some(ident) =
1555 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1558 Ok(dummy_arg(ident))
1564 self.eat_incorrect_doc_comment_for_param_type();
1565 (pat, self.parse_ty_for_param()?)
1567 debug!("parse_param_general ident_to_pat");
1568 let parser_snapshot_before_ty = self.clone();
1569 self.eat_incorrect_doc_comment_for_param_type();
1570 let mut ty = self.parse_ty_for_param();
1572 && self.token != token::Comma
1573 && self.token != token::CloseDelim(token::Paren)
1575 // This wasn't actually a type, but a pattern looking like a type,
1576 // so we are going to rollback and re-parse for recovery.
1577 ty = self.unexpected();
1581 let ident = Ident::new(kw::Invalid, self.prev_token.span);
1582 let bm = BindingMode::ByValue(Mutability::Not);
1583 let pat = self.mk_pat_ident(ty.span, bm, ident);
1586 // If this is a C-variadic argument and we hit an error, return the error.
1587 Err(err) if self.token == token::DotDotDot => return Err(err),
1588 // Recover from attempting to parse the argument as a type without pattern.
1591 mem::replace(self, parser_snapshot_before_ty);
1592 self.recover_arg_parse()?
1597 let span = lo.to(self.token.span);
1600 attrs: attrs.into(),
1601 id: ast::DUMMY_NODE_ID,
1602 is_placeholder: false,
1609 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1610 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1611 // Extract an identifier *after* having confirmed that the token is one.
1612 let expect_self_ident = |this: &mut Self| {
1613 match this.normalized_token.kind {
1614 // Preserve hygienic context.
1615 token::Ident(name, _) => {
1617 Ident::new(name, this.normalized_prev_token.span)
1619 _ => unreachable!(),
1622 // Is `self` `n` tokens ahead?
1623 let is_isolated_self = |this: &Self, n| {
1624 this.is_keyword_ahead(n, &[kw::SelfLower])
1625 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1627 // Is `mut self` `n` tokens ahead?
1628 let is_isolated_mut_self =
1629 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1630 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1631 let parse_self_possibly_typed = |this: &mut Self, m| {
1632 let eself_ident = expect_self_ident(this);
1633 let eself_hi = this.prev_token.span;
1634 let eself = if this.eat(&token::Colon) {
1635 SelfKind::Explicit(this.parse_ty()?, m)
1639 Ok((eself, eself_ident, eself_hi))
1641 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1642 let recover_self_ptr = |this: &mut Self| {
1643 let msg = "cannot pass `self` by raw pointer";
1644 let span = this.token.span;
1645 this.struct_span_err(span, msg).span_label(span, msg).emit();
1647 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
1650 // Parse optional `self` parameter of a method.
1651 // Only a limited set of initial token sequences is considered `self` parameters; anything
1652 // else is parsed as a normal function parameter list, so some lookahead is required.
1653 let eself_lo = self.token.span;
1654 let (eself, eself_ident, eself_hi) = match self.normalized_token.kind {
1655 token::BinOp(token::And) => {
1656 let eself = if is_isolated_self(self, 1) {
1659 SelfKind::Region(None, Mutability::Not)
1660 } else if is_isolated_mut_self(self, 1) {
1664 SelfKind::Region(None, Mutability::Mut)
1665 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1668 let lt = self.expect_lifetime();
1669 SelfKind::Region(Some(lt), Mutability::Not)
1670 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1673 let lt = self.expect_lifetime();
1675 SelfKind::Region(Some(lt), Mutability::Mut)
1680 (eself, expect_self_ident(self), self.prev_token.span)
1683 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1685 recover_self_ptr(self)?
1687 // `*mut self` and `*const self`
1688 token::BinOp(token::Star)
1689 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1693 recover_self_ptr(self)?
1695 // `self` and `self: TYPE`
1696 token::Ident(..) if is_isolated_self(self, 0) => {
1697 parse_self_possibly_typed(self, Mutability::Not)?
1699 // `mut self` and `mut self: TYPE`
1700 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1702 parse_self_possibly_typed(self, Mutability::Mut)?
1704 _ => return Ok(None),
1707 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1708 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1711 fn is_named_param(&self) -> bool {
1712 let offset = match self.token.kind {
1713 token::Interpolated(ref nt) => match **nt {
1714 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1717 token::BinOp(token::And) | token::AndAnd => 1,
1718 _ if self.token.is_keyword(kw::Mut) => 1,
1722 self.look_ahead(offset, |t| t.is_ident())
1723 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1726 fn recover_first_param(&mut self) -> &'static str {
1728 .parse_outer_attributes()
1729 .and_then(|_| self.parse_self_param())
1730 .map_err(|mut e| e.cancel())
1732 Ok(Some(_)) => "method",