1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath};
3 use super::{FollowedByType, Parser, PathStyle};
5 use crate::maybe_whole;
7 use rustc_ast_pretty::pprust;
8 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
9 use rustc_span::source_map::{self, Span};
10 use rustc_span::symbol::{kw, sym, Symbol};
11 use syntax::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
12 use syntax::ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind};
13 use syntax::ast::{Async, Const, Defaultness, IsAuto, PathSegment, Unsafe, UseTree, UseTreeKind};
14 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
15 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
16 use syntax::ast::{FnHeader, ForeignItem, Mutability, Visibility, VisibilityKind};
19 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
24 pub(super) type ItemInfo = (Ident, ItemKind);
27 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
28 self.parse_item_(|_| true).map(|i| i.map(P))
31 fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
32 let attrs = self.parse_outer_attributes()?;
33 self.parse_item_common(attrs, true, false, req_name)
36 pub(super) fn parse_item_common(
38 mut attrs: Vec<Attribute>,
42 ) -> PResult<'a, Option<Item>> {
43 maybe_whole!(self, NtItem, |item| {
45 mem::swap(&mut item.attrs, &mut attrs);
46 item.attrs.extend(attrs);
47 Some(item.into_inner())
50 let mut unclosed_delims = vec![];
51 let (mut item, tokens) = self.collect_tokens(|this| {
52 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
53 unclosed_delims.append(&mut this.unclosed_delims);
56 self.unclosed_delims.append(&mut unclosed_delims);
58 // Once we've parsed an item and recorded the tokens we got while
59 // parsing we may want to store `tokens` into the item we're about to
60 // return. Note, though, that we specifically didn't capture tokens
61 // related to outer attributes. The `tokens` field here may later be
62 // used with procedural macros to convert this item back into a token
63 // stream, but during expansion we may be removing attributes as we go
66 // If we've got inner attributes then the `tokens` we've got above holds
67 // these inner attributes. If an inner attribute is expanded we won't
68 // actually remove it from the token stream, so we'll just keep yielding
69 // it (bad!). To work around this case for now we just avoid recording
70 // `tokens` if we detect any inner attributes. This should help keep
71 // expansion correct, but we should fix this bug one day!
72 if let Some(item) = &mut item {
73 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
74 item.tokens = Some(tokens);
80 fn parse_item_common_(
82 mut attrs: Vec<Attribute>,
86 ) -> PResult<'a, Option<Item>> {
87 let lo = self.token.span;
88 let vis = self.parse_visibility(FollowedByType::No)?;
89 let mut def = self.parse_defaultness();
90 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
91 if let Some((ident, kind)) = kind {
92 self.error_on_unconsumed_default(def, &kind);
93 let span = lo.to(self.prev_span);
94 let id = DUMMY_NODE_ID;
95 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
96 return Ok(Some(item));
99 // At this point, we have failed to parse an item.
100 self.error_on_unmatched_vis(&vis);
101 self.error_on_unmatched_defaultness(def);
103 self.recover_attrs_no_item(&attrs)?;
108 /// Error in-case a non-inherited visibility was parsed but no item followed.
109 fn error_on_unmatched_vis(&self, vis: &Visibility) {
110 if let VisibilityKind::Inherited = vis.node {
113 let vs = pprust::vis_to_string(&vis);
114 let vs = vs.trim_end();
115 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
116 .span_label(vis.span, "the visibility")
117 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
121 /// Error in-case a `default` was parsed but no item followed.
122 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
123 if let Defaultness::Default(sp) = def {
124 self.struct_span_err(sp, "`default` is not followed by an item")
125 .span_label(sp, "the `default` qualifier")
126 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
131 /// Error in-case `default` was parsed in an in-appropriate context.
132 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
133 if let Defaultness::Default(span) = def {
134 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
135 self.struct_span_err(span, &msg)
136 .span_label(span, "`default` because of this")
137 .note("only associated `fn`, `const`, and `type` items can be `default`")
142 /// Parses one of the items allowed by the flags.
145 attrs: &mut Vec<Attribute>,
146 macros_allowed: bool,
149 def: &mut Defaultness,
151 ) -> PResult<'a, Option<ItemInfo>> {
152 let mut def = || mem::replace(def, Defaultness::Final);
154 let info = if self.eat_keyword(kw::Use) {
156 let tree = self.parse_use_tree()?;
158 (Ident::invalid(), ItemKind::Use(P(tree)))
159 } else if self.check_fn_front_matter() {
161 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name)?;
162 (ident, ItemKind::Fn(def(), sig, generics, body))
163 } else if self.eat_keyword(kw::Extern) {
164 if self.eat_keyword(kw::Crate) {
166 self.parse_item_extern_crate()?
169 self.parse_item_foreign_mod(attrs)?
171 } else if self.is_static_global() {
173 self.bump(); // `static`
174 let m = self.parse_mutability();
175 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
176 (ident, ItemKind::Static(ty, m, expr))
177 } else if let Const::Yes(const_span) = self.parse_constness() {
179 self.recover_const_mut(const_span);
180 let (ident, ty, expr) = self.parse_item_global(None)?;
181 (ident, ItemKind::Const(def(), ty, expr))
182 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
184 self.parse_item_trait(attrs, lo)?
185 } else if self.check_keyword(kw::Impl)
186 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
189 self.parse_item_impl(attrs, def())?
190 } else if self.eat_keyword(kw::Mod) {
192 self.parse_item_mod(attrs)?
193 } else if self.eat_keyword(kw::Type) {
195 self.parse_type_alias(def())?
196 } else if self.eat_keyword(kw::Enum) {
198 self.parse_item_enum()?
199 } else if self.eat_keyword(kw::Struct) {
201 self.parse_item_struct()?
202 } else if self.is_kw_followed_by_ident(kw::Union) {
204 self.bump(); // `union`
205 self.parse_item_union()?
206 } else if self.eat_keyword(kw::Macro) {
208 self.parse_item_decl_macro(lo)?
209 } else if self.is_macro_rules_item() {
211 self.parse_item_macro_rules(vis)?
212 } else if vis.node.is_pub() && self.isnt_macro_invocation() {
213 self.recover_missing_kw_before_item()?;
215 } else if macros_allowed && self.token.is_path_start() {
216 // MACRO INVOCATION ITEM
217 (Ident::invalid(), ItemKind::Mac(self.parse_item_macro(vis)?))
224 /// When parsing a statement, would the start of a path be an item?
225 pub(super) fn is_path_start_item(&mut self) -> bool {
226 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
227 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
228 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
229 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
230 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
233 /// Are we sure this could not possibly be a macro invocation?
234 fn isnt_macro_invocation(&mut self) -> bool {
235 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
238 /// Recover on encountering a struct or method definition where the user
239 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
240 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
241 // Space between `pub` keyword and the identifier
244 // ^^^ `sp` points here
245 let sp = self.prev_span.between(self.token.span);
246 let full_sp = self.prev_span.to(self.token.span);
247 let ident_sp = self.token.span;
248 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
249 // possible public struct definition where `struct` was forgotten
250 let ident = self.parse_ident().unwrap();
251 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
252 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
253 err.span_suggestion_short(
257 Applicability::MaybeIncorrect, // speculative
260 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
261 let ident = self.parse_ident().unwrap();
263 let kw_name = self.recover_first_param();
264 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
265 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
266 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
268 ("fn", kw_name, false)
269 } else if self.check(&token::OpenDelim(token::Brace)) {
271 ("fn", kw_name, false)
272 } else if self.check(&token::Colon) {
276 ("fn` or `struct", "function or struct", true)
279 let msg = format!("missing `{}` for {} definition", kw, kw_name);
280 let mut err = self.struct_span_err(sp, &msg);
282 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
284 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
285 err.span_suggestion_short(
289 Applicability::MachineApplicable,
292 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
295 "if you meant to call a macro, try",
296 format!("{}!", snippet),
297 // this is the `ambiguous` conditional branch
298 Applicability::MaybeIncorrect,
302 "if you meant to call a macro, remove the `pub` \
303 and add a trailing `!` after the identifier",
308 } else if self.look_ahead(1, |t| *t == token::Lt) {
309 let ident = self.parse_ident().unwrap();
310 self.eat_to_tokens(&[&token::Gt]);
312 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
313 ("fn", self.recover_first_param(), false)
314 } else if self.check(&token::OpenDelim(token::Brace)) {
315 ("struct", "struct", false)
317 ("fn` or `struct", "function or struct", true)
319 let msg = format!("missing `{}` for {} definition", kw, kw_name);
320 let mut err = self.struct_span_err(sp, &msg);
322 err.span_suggestion_short(
324 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
326 Applicability::MachineApplicable,
335 /// Parses an item macro, e.g., `item!();`.
336 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, Mac> {
337 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
338 self.expect(&token::Not)?; // `!`
339 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
340 self.eat_semi_for_macro_if_needed(&args);
341 self.complain_if_pub_macro(vis, false);
342 Ok(Mac { path, args, prior_type_ascription: self.last_type_ascription })
345 /// Recover if we parsed attributes and expected an item but there was none.
346 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
347 let (start, end) = match attrs {
350 [x0, .., xn] => (x0, xn),
352 let msg = if end.is_doc_comment() {
353 "expected item after doc comment"
355 "expected item after attributes"
357 let mut err = self.struct_span_err(end.span, msg);
358 if end.is_doc_comment() {
359 err.span_label(end.span, "this doc comment doesn't document anything");
361 if let [.., penultimate, _] = attrs {
362 err.span_label(start.span.to(penultimate.span), "other attributes here");
367 fn is_async_fn(&self) -> bool {
368 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
371 /// Parses an implementation item.
374 /// impl<'a, T> TYPE { /* impl items */ }
375 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
376 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
377 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
380 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
382 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
383 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
387 attrs: &mut Vec<Attribute>,
388 defaultness: Defaultness,
389 ) -> PResult<'a, ItemInfo> {
390 let unsafety = self.parse_unsafety();
391 self.expect_keyword(kw::Impl)?;
393 // First, parse generic parameters if necessary.
394 let mut generics = if self.choose_generics_over_qpath() {
395 self.parse_generics()?
397 let mut generics = Generics::default();
399 // /\ this is where `generics.span` should point when there are no type params.
400 generics.span = self.prev_span.shrink_to_hi();
404 let constness = self.parse_constness();
405 if let Const::Yes(span) = constness {
406 self.sess.gated_spans.gate(sym::const_trait_impl, span);
409 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
410 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
412 ast::ImplPolarity::Negative
414 ast::ImplPolarity::Positive
417 // Parse both types and traits as a type, then reinterpret if necessary.
418 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
419 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
421 let span = self.prev_span.between(self.token.span);
422 self.struct_span_err(span, "missing trait in a trait impl").emit();
423 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
428 // If `for` is missing we try to recover.
429 let has_for = self.eat_keyword(kw::For);
430 let missing_for_span = self.prev_span.between(self.token.span);
432 let ty_second = if self.token == token::DotDot {
433 // We need to report this error after `cfg` expansion for compatibility reasons
434 self.bump(); // `..`, do not add it to expected tokens
435 Some(self.mk_ty(self.prev_span, TyKind::Err))
436 } else if has_for || self.token.can_begin_type() {
437 Some(self.parse_ty()?)
442 generics.where_clause = self.parse_where_clause()?;
444 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
446 let item_kind = match ty_second {
448 // impl Trait for Type
450 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
451 .span_suggestion_short(
455 Applicability::MachineApplicable,
460 let ty_first = ty_first.into_inner();
461 let path = match ty_first.kind {
462 // This notably includes paths passed through `ty` macro fragments (#46438).
463 TyKind::Path(None, path) => path,
465 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
466 err_path(ty_first.span)
469 let trait_ref = TraitRef { path, ref_id: ty_first.id };
477 of_trait: Some(trait_ref),
497 Ok((Ident::invalid(), item_kind))
500 fn parse_item_list<T>(
502 attrs: &mut Vec<Attribute>,
503 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
504 ) -> PResult<'a, Vec<T>> {
505 let open_brace_span = self.token.span;
506 self.expect(&token::OpenDelim(token::Brace))?;
507 attrs.append(&mut self.parse_inner_attributes()?);
509 let mut items = Vec::new();
510 while !self.eat(&token::CloseDelim(token::Brace)) {
511 if self.recover_doc_comment_before_brace() {
514 match parse_item(self) {
516 // We have to bail or we'll potentially never make progress.
517 let non_item_span = self.token.span;
518 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
519 self.struct_span_err(non_item_span, "non-item in item list")
520 .span_label(open_brace_span, "item list starts here")
521 .span_label(non_item_span, "non-item starts here")
522 .span_label(self.prev_span, "item list ends here")
526 Ok(Some(item)) => items.extend(item),
528 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
529 err.span_label(open_brace_span, "while parsing this item list starting here")
530 .span_label(self.prev_span, "the item list ends here")
539 /// Recover on a doc comment before `}`.
540 fn recover_doc_comment_before_brace(&mut self) -> bool {
541 if let token::DocComment(_) = self.token.kind {
542 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
547 "found a documentation comment that doesn't document anything",
549 .span_label(self.token.span, "this doc comment doesn't document anything")
551 "doc comments must come before what they document, maybe a \
552 comment was intended with `//`?",
562 /// Parses defaultness (i.e., `default` or nothing).
563 fn parse_defaultness(&mut self) -> Defaultness {
564 // We are interested in `default` followed by another identifier.
565 // However, we must avoid keywords that occur as binary operators.
566 // Currently, the only applicable keyword is `as` (`default as Ty`).
567 if self.check_keyword(kw::Default)
568 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
570 self.bump(); // `default`
571 Defaultness::Default(self.prev_span)
577 /// Is this an `(unsafe auto? | auto) trait` item?
578 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
580 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
582 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
585 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
586 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
587 let unsafety = self.parse_unsafety();
588 // Parse optional `auto` prefix.
589 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
591 self.expect_keyword(kw::Trait)?;
592 let ident = self.parse_ident()?;
593 let mut tps = self.parse_generics()?;
595 // Parse optional colon and supertrait bounds.
596 let had_colon = self.eat(&token::Colon);
597 let span_at_colon = self.prev_span;
599 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
601 let span_before_eq = self.prev_span;
602 if self.eat(&token::Eq) {
603 // It's a trait alias.
605 let span = span_at_colon.to(span_before_eq);
606 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
609 let bounds = self.parse_generic_bounds(None)?;
610 tps.where_clause = self.parse_where_clause()?;
613 let whole_span = lo.to(self.prev_span);
614 if is_auto == IsAuto::Yes {
615 let msg = "trait aliases cannot be `auto`";
616 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
618 if let Unsafe::Yes(_) = unsafety {
619 let msg = "trait aliases cannot be `unsafe`";
620 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
623 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
625 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
627 // It's a normal trait.
628 tps.where_clause = self.parse_where_clause()?;
629 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
630 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
634 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
635 maybe_whole!(self, NtImplItem, |x| Some(Some(x)));
636 self.parse_assoc_item(|_| true)
639 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
640 maybe_whole!(self, NtTraitItem, |x| Some(Some(x)));
641 // This is somewhat dubious; We don't want to allow
642 // param names to be left off if there is a definition...
644 // We don't allow param names to be left off in edition 2018.
645 self.parse_assoc_item(|t| t.span.rust_2018())
648 /// Parses associated items.
649 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
650 Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
651 let kind = match kind {
652 ItemKind::Mac(a) => AssocItemKind::Macro(a),
653 ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d),
654 ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d),
655 ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
656 ItemKind::Static(a, _, b) => {
657 self.struct_span_err(span, "associated `static` items are not allowed").emit();
658 AssocItemKind::Const(Defaultness::Final, a, b)
660 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
662 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
666 /// Parses a `type` alias with the following grammar:
668 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
670 /// The `"type"` has already been eaten.
671 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
672 let ident = self.parse_ident()?;
673 let mut generics = self.parse_generics()?;
675 // Parse optional colon and param bounds.
677 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
678 generics.where_clause = self.parse_where_clause()?;
680 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
683 Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
686 /// Parses a `UseTree`.
689 /// USE_TREE = [`::`] `*` |
690 /// [`::`] `{` USE_TREE_LIST `}` |
692 /// PATH `::` `{` USE_TREE_LIST `}` |
693 /// PATH [`as` IDENT]
695 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
696 let lo = self.token.span;
698 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
699 let kind = if self.check(&token::OpenDelim(token::Brace))
700 || self.check(&token::BinOp(token::Star))
701 || self.is_import_coupler()
703 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
704 let mod_sep_ctxt = self.token.span.ctxt();
705 if self.eat(&token::ModSep) {
708 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
711 self.parse_use_tree_glob_or_nested()?
713 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
714 prefix = self.parse_path(PathStyle::Mod)?;
716 if self.eat(&token::ModSep) {
717 self.parse_use_tree_glob_or_nested()?
719 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
723 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
726 /// Parses `*` or `{...}`.
727 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
728 Ok(if self.eat(&token::BinOp(token::Star)) {
731 UseTreeKind::Nested(self.parse_use_tree_list()?)
735 /// Parses a `UseTreeKind::Nested(list)`.
738 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
740 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
741 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
745 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
746 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
749 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
750 match self.token.kind {
751 token::Ident(name @ kw::Underscore, false) => {
752 let span = self.token.span;
754 Ok(Ident::new(name, span))
756 _ => self.parse_ident(),
760 /// Parses `extern crate` links.
765 /// extern crate foo;
766 /// extern crate bar as foo;
768 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
769 // Accept `extern crate name-like-this` for better diagnostics
770 let orig_name = self.parse_crate_name_with_dashes()?;
771 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
772 (rename, Some(orig_name.name))
777 Ok((item_name, ItemKind::ExternCrate(orig_name)))
780 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
781 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
782 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
784 let mut ident = if self.token.is_keyword(kw::SelfLower) {
785 self.parse_path_segment_ident()
789 let mut idents = vec![];
790 let mut replacement = vec![];
791 let mut fixed_crate_name = false;
792 // Accept `extern crate name-like-this` for better diagnostics.
793 let dash = token::BinOp(token::BinOpToken::Minus);
794 if self.token == dash {
795 // Do not include `-` as part of the expected tokens list.
796 while self.eat(&dash) {
797 fixed_crate_name = true;
798 replacement.push((self.prev_span, "_".to_string()));
799 idents.push(self.parse_ident()?);
802 if fixed_crate_name {
803 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
804 let mut fixed_name = format!("{}", ident.name);
806 fixed_name.push_str(&format!("_{}", part.name));
808 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
810 self.struct_span_err(fixed_name_sp, error_msg)
811 .span_label(fixed_name_sp, "dash-separated idents are not valid")
812 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
818 /// Parses `extern` for foreign ABIs modules.
820 /// `extern` is expected to have been consumed before calling this method.
824 /// ```ignore (only-for-syntax-highlight)
828 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
829 let abi = self.parse_abi(); // ABI?
830 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
831 let module = ast::ForeignMod { abi, items };
832 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
835 /// Parses a foreign item (one in an `extern { ... }` block).
836 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
837 maybe_whole!(self, NtForeignItem, |item| Some(Some(item)));
839 Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
840 let kind = match kind {
841 ItemKind::Mac(a) => ForeignItemKind::Macro(a),
842 ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d),
843 ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d),
844 ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
845 ItemKind::Const(_, a, b) => {
846 self.error_on_foreign_const(span, ident);
847 ForeignItemKind::Static(a, Mutability::Not, b)
849 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
851 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
855 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
856 let span = self.sess.source_map().def_span(span);
857 let msg = format!("{} is not supported in {}", kind.descr(), ctx);
858 self.struct_span_err(span, &msg).emit();
862 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
863 self.struct_span_err(ident.span, "extern items cannot be `const`")
865 span.with_hi(ident.span.lo()),
866 "try using a static value",
867 "static ".to_string(),
868 Applicability::MachineApplicable,
870 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
874 fn is_static_global(&mut self) -> bool {
875 if self.check_keyword(kw::Static) {
876 // Check if this could be a closure.
877 !self.look_ahead(1, |token| {
878 if token.is_keyword(kw::Move) {
882 token::BinOp(token::Or) | token::OrOr => true,
891 /// Recover on `const mut` with `const` already eaten.
892 fn recover_const_mut(&mut self, const_span: Span) {
893 if self.eat_keyword(kw::Mut) {
894 let span = self.prev_span;
895 self.struct_span_err(span, "const globals cannot be mutable")
896 .span_label(span, "cannot be mutable")
899 "you might want to declare a static instead",
901 Applicability::MaybeIncorrect,
907 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
908 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
910 /// When `m` is `"const"`, `$ident` may also be `"_"`.
911 fn parse_item_global(
913 m: Option<Mutability>,
914 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
915 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
917 // Parse the type of a `const` or `static mut?` item.
918 // That is, the `":" $ty` fragment.
919 let ty = if self.eat(&token::Colon) {
922 self.recover_missing_const_type(id, m)
925 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
930 /// We were supposed to parse `:` but the `:` was missing.
931 /// This means that the type is missing.
932 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
933 // Construct the error and stash it away with the hope
934 // that typeck will later enrich the error with a type.
936 Some(Mutability::Mut) => "static mut",
937 Some(Mutability::Not) => "static",
940 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
943 "provide a type for the item",
944 format!("{}: <type>", id),
945 Applicability::HasPlaceholders,
947 err.stash(id.span, StashKey::ItemNoType);
949 // The user intended that the type be inferred,
950 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
951 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
954 /// Parses an enum declaration.
955 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
956 let id = self.parse_ident()?;
957 let mut generics = self.parse_generics()?;
958 generics.where_clause = self.parse_where_clause()?;
961 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
966 let enum_definition =
967 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
968 Ok((id, ItemKind::Enum(enum_definition, generics)))
971 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
972 let variant_attrs = self.parse_outer_attributes()?;
973 let vlo = self.token.span;
975 let vis = self.parse_visibility(FollowedByType::No)?;
976 if !self.recover_nested_adt_item(kw::Enum)? {
979 let ident = self.parse_ident()?;
981 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
982 // Parse a struct variant.
983 let (fields, recovered) = self.parse_record_struct_body()?;
984 VariantData::Struct(fields, recovered)
985 } else if self.check(&token::OpenDelim(token::Paren)) {
986 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
988 VariantData::Unit(DUMMY_NODE_ID)
992 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
994 let vr = ast::Variant {
998 attrs: variant_attrs,
1001 span: vlo.to(self.prev_span),
1002 is_placeholder: false,
1008 /// Parses `struct Foo { ... }`.
1009 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1010 let class_name = self.parse_ident()?;
1012 let mut generics = self.parse_generics()?;
1014 // There is a special case worth noting here, as reported in issue #17904.
1015 // If we are parsing a tuple struct it is the case that the where clause
1016 // should follow the field list. Like so:
1018 // struct Foo<T>(T) where T: Copy;
1020 // If we are parsing a normal record-style struct it is the case
1021 // that the where clause comes before the body, and after the generics.
1022 // So if we look ahead and see a brace or a where-clause we begin
1023 // parsing a record style struct.
1025 // Otherwise if we look ahead and see a paren we parse a tuple-style
1028 let vdata = if self.token.is_keyword(kw::Where) {
1029 generics.where_clause = self.parse_where_clause()?;
1030 if self.eat(&token::Semi) {
1031 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1032 VariantData::Unit(DUMMY_NODE_ID)
1034 // If we see: `struct Foo<T> where T: Copy { ... }`
1035 let (fields, recovered) = self.parse_record_struct_body()?;
1036 VariantData::Struct(fields, recovered)
1038 // No `where` so: `struct Foo<T>;`
1039 } else if self.eat(&token::Semi) {
1040 VariantData::Unit(DUMMY_NODE_ID)
1041 // Record-style struct definition
1042 } else if self.token == token::OpenDelim(token::Brace) {
1043 let (fields, recovered) = self.parse_record_struct_body()?;
1044 VariantData::Struct(fields, recovered)
1045 // Tuple-style struct definition with optional where-clause.
1046 } else if self.token == token::OpenDelim(token::Paren) {
1047 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1048 generics.where_clause = self.parse_where_clause()?;
1049 self.expect_semi()?;
1052 let token_str = super::token_descr(&self.token);
1054 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1057 let mut err = self.struct_span_err(self.token.span, msg);
1058 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1062 Ok((class_name, ItemKind::Struct(vdata, generics)))
1065 /// Parses `union Foo { ... }`.
1066 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1067 let class_name = self.parse_ident()?;
1069 let mut generics = self.parse_generics()?;
1071 let vdata = if self.token.is_keyword(kw::Where) {
1072 generics.where_clause = self.parse_where_clause()?;
1073 let (fields, recovered) = self.parse_record_struct_body()?;
1074 VariantData::Struct(fields, recovered)
1075 } else if self.token == token::OpenDelim(token::Brace) {
1076 let (fields, recovered) = self.parse_record_struct_body()?;
1077 VariantData::Struct(fields, recovered)
1079 let token_str = super::token_descr(&self.token);
1080 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1081 let mut err = self.struct_span_err(self.token.span, msg);
1082 err.span_label(self.token.span, "expected `where` or `{` after union name");
1086 Ok((class_name, ItemKind::Union(vdata, generics)))
1089 fn parse_record_struct_body(
1091 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1092 let mut fields = Vec::new();
1093 let mut recovered = false;
1094 if self.eat(&token::OpenDelim(token::Brace)) {
1095 while self.token != token::CloseDelim(token::Brace) {
1096 let field = self.parse_struct_decl_field().map_err(|e| {
1097 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1102 Ok(field) => fields.push(field),
1109 self.eat(&token::CloseDelim(token::Brace));
1111 let token_str = super::token_descr(&self.token);
1112 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1113 let mut err = self.struct_span_err(self.token.span, msg);
1114 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1118 Ok((fields, recovered))
1121 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1122 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1123 // Unit like structs are handled in parse_item_struct function
1124 self.parse_paren_comma_seq(|p| {
1125 let attrs = p.parse_outer_attributes()?;
1126 let lo = p.token.span;
1127 let vis = p.parse_visibility(FollowedByType::Yes)?;
1128 let ty = p.parse_ty()?;
1130 span: lo.to(ty.span),
1136 is_placeholder: false,
1142 /// Parses an element of a struct declaration.
1143 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1144 let attrs = self.parse_outer_attributes()?;
1145 let lo = self.token.span;
1146 let vis = self.parse_visibility(FollowedByType::No)?;
1147 self.parse_single_struct_field(lo, vis, attrs)
1150 /// Parses a structure field declaration.
1151 fn parse_single_struct_field(
1155 attrs: Vec<Attribute>,
1156 ) -> PResult<'a, StructField> {
1157 let mut seen_comma: bool = false;
1158 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1159 if self.token == token::Comma {
1162 match self.token.kind {
1166 token::CloseDelim(token::Brace) => {}
1167 token::DocComment(_) => {
1168 let previous_span = self.prev_span;
1169 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1170 self.bump(); // consume the doc comment
1171 let comma_after_doc_seen = self.eat(&token::Comma);
1172 // `seen_comma` is always false, because we are inside doc block
1173 // condition is here to make code more readable
1174 if !seen_comma && comma_after_doc_seen {
1177 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1181 let sp = self.sess.source_map().next_point(previous_span);
1182 err.span_suggestion(
1184 "missing comma here",
1186 Applicability::MachineApplicable,
1193 let sp = self.prev_span.shrink_to_hi();
1194 let mut err = self.struct_span_err(
1196 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1198 if self.token.is_ident() {
1199 // This is likely another field; emit the diagnostic and keep going
1200 err.span_suggestion(
1202 "try adding a comma",
1204 Applicability::MachineApplicable,
1215 /// Parses a structure field.
1216 fn parse_name_and_ty(
1220 attrs: Vec<Attribute>,
1221 ) -> PResult<'a, StructField> {
1222 let name = self.parse_ident()?;
1223 self.expect(&token::Colon)?;
1224 let ty = self.parse_ty()?;
1226 span: lo.to(self.prev_span),
1232 is_placeholder: false,
1236 /// Parses a declarative macro 2.0 definition.
1237 /// The `macro` keyword has already been parsed.
1239 /// MacBody = "{" TOKEN_STREAM "}" ;
1240 /// MacParams = "(" TOKEN_STREAM ")" ;
1241 /// DeclMac = "macro" Ident MacParams? MacBody ;
1243 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1244 let ident = self.parse_ident()?;
1245 let body = if self.check(&token::OpenDelim(token::Brace)) {
1246 self.parse_mac_args()? // `MacBody`
1247 } else if self.check(&token::OpenDelim(token::Paren)) {
1248 let params = self.parse_token_tree(); // `MacParams`
1249 let pspan = params.span();
1250 if !self.check(&token::OpenDelim(token::Brace)) {
1251 return self.unexpected();
1253 let body = self.parse_token_tree(); // `MacBody`
1254 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1255 let bspan = body.span();
1256 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1257 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1258 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1259 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1261 return self.unexpected();
1264 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1265 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1268 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1269 fn is_macro_rules_item(&mut self) -> bool {
1270 self.check_keyword(kw::MacroRules)
1271 && self.look_ahead(1, |t| *t == token::Not)
1272 && self.look_ahead(2, |t| t.is_ident())
1275 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1276 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1277 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1278 self.expect(&token::Not)?; // `!`
1280 let ident = self.parse_ident()?;
1281 let body = self.parse_mac_args()?;
1282 self.eat_semi_for_macro_if_needed(&body);
1283 self.complain_if_pub_macro(vis, true);
1285 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1288 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1289 /// If that's not the case, emit an error.
1290 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1291 if let VisibilityKind::Inherited = vis.node {
1295 let vstr = pprust::vis_to_string(vis);
1296 let vstr = vstr.trim_end();
1298 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1299 self.struct_span_err(vis.span, &msg)
1302 "try exporting the macro",
1303 "#[macro_export]".to_owned(),
1304 Applicability::MaybeIncorrect, // speculative
1308 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1311 "remove the visibility",
1313 Applicability::MachineApplicable,
1315 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1320 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1321 if args.need_semicolon() && !self.eat(&token::Semi) {
1322 self.report_invalid_macro_expansion_item(args);
1326 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1327 let span = args.span().expect("undelimited macro call");
1328 let mut err = self.struct_span_err(
1330 "macros that expand to items must be delimited with braces or followed by a semicolon",
1332 if self.unclosed_delims.is_empty() {
1333 let DelimSpan { open, close } = match args {
1334 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1335 MacArgs::Delimited(dspan, ..) => *dspan,
1337 err.multipart_suggestion(
1338 "change the delimiters to curly braces",
1339 vec![(open, "{".to_string()), (close, '}'.to_string())],
1340 Applicability::MaybeIncorrect,
1343 err.span_suggestion(
1345 "change the delimiters to curly braces",
1346 " { /* items */ }".to_string(),
1347 Applicability::HasPlaceholders,
1350 err.span_suggestion(
1351 span.shrink_to_hi(),
1354 Applicability::MaybeIncorrect,
1359 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1360 /// it is, we try to parse the item and report error about nested types.
1361 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1362 if (self.token.is_keyword(kw::Enum)
1363 || self.token.is_keyword(kw::Struct)
1364 || self.token.is_keyword(kw::Union))
1365 && self.look_ahead(1, |t| t.is_ident())
1367 let kw_token = self.token.clone();
1368 let kw_str = pprust::token_to_string(&kw_token);
1369 let item = self.parse_item()?;
1371 self.struct_span_err(
1373 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1377 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1379 Applicability::MaybeIncorrect,
1382 // We successfully parsed the item but we must inform the caller about nested problem.
1389 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1391 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1392 type ReqName = fn(&token::Token) -> bool;
1394 /// Parsing of functions and methods.
1395 impl<'a> Parser<'a> {
1396 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1399 attrs: &mut Vec<Attribute>,
1401 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1402 let header = self.parse_fn_front_matter()?; // `const ... fn`
1403 let ident = self.parse_ident()?; // `foo`
1404 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1405 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1406 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1407 let body = self.parse_fn_body(attrs)?; // `;` or `{ ... }`.
1408 Ok((ident, FnSig { header, decl }, generics, body))
1411 /// Parse the "body" of a function.
1412 /// This can either be `;` when there's no body,
1413 /// or e.g. a block when the function is a provided one.
1414 fn parse_fn_body(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, Option<P<Block>>> {
1415 let (inner_attrs, body) = match self.token.kind {
1420 token::OpenDelim(token::Brace) => {
1421 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1424 token::Interpolated(ref nt) => match **nt {
1425 token::NtBlock(..) => {
1426 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1429 _ => return self.expected_semi_or_open_brace(),
1431 _ => return self.expected_semi_or_open_brace(),
1433 attrs.extend(inner_attrs);
1437 /// Is the current token the start of an `FnHeader` / not a valid parse?
1438 fn check_fn_front_matter(&mut self) -> bool {
1439 // We use an over-approximation here.
1440 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1441 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1442 self.check_keyword(kw::Fn) // Definitely an `fn`.
1443 // `$qual fn` or `$qual $qual`:
1444 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1445 && self.look_ahead(1, |t| {
1446 // ...qualified and then `fn`, e.g. `const fn`.
1447 t.is_keyword(kw::Fn)
1448 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1449 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1452 || self.check_keyword(kw::Extern)
1453 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1454 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1457 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1458 /// up to and including the `fn` keyword. The formal grammar is:
1461 /// Extern = "extern" StringLit ;
1462 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1463 /// FnFrontMatter = FnQual? "fn" ;
1465 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1466 let constness = self.parse_constness();
1467 let asyncness = self.parse_asyncness();
1468 let unsafety = self.parse_unsafety();
1469 let ext = self.parse_extern()?;
1471 if let Async::Yes { span, .. } = asyncness {
1472 self.ban_async_in_2015(span);
1475 if !self.eat_keyword(kw::Fn) {
1476 // It is possible for `expect_one_of` to recover given the contents of
1477 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1478 // account for this.
1479 if !self.expect_one_of(&[], &[])? {
1484 Ok(FnHeader { constness, unsafety, asyncness, ext })
1487 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1488 fn ban_async_in_2015(&self, span: Span) {
1489 if span.rust_2015() {
1490 let diag = self.diagnostic();
1491 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1492 .note("to use `async fn`, switch to Rust 2018")
1493 .help("set `edition = \"2018\"` in `Cargo.toml`")
1494 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1499 /// Parses the parameter list and result type of a function declaration.
1500 pub(super) fn parse_fn_decl(
1503 ret_allow_plus: AllowPlus,
1504 ) -> PResult<'a, P<FnDecl>> {
1506 inputs: self.parse_fn_params(req_name)?,
1507 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1511 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1512 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1513 let mut first_param = true;
1514 // Parse the arguments, starting out with `self` being allowed...
1515 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1516 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1518 let lo = p.prev_span;
1519 // Skip every token until next possible arg or end.
1520 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1521 // Create a placeholder argument for proper arg count (issue #34264).
1522 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1524 // ...now that we've parsed the first argument, `self` is no longer allowed.
1525 first_param = false;
1528 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1529 self.deduplicate_recovered_params_names(&mut params);
1533 /// Parses a single function parameter.
1535 /// - `self` is syntactically allowed when `first_param` holds.
1536 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1537 let lo = self.token.span;
1538 let attrs = self.parse_outer_attributes()?;
1540 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1541 if let Some(mut param) = self.parse_self_param()? {
1542 param.attrs = attrs.into();
1543 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1546 let is_name_required = match self.token.kind {
1547 token::DotDotDot => false,
1548 _ => req_name(&self.token),
1550 let (pat, ty) = if is_name_required || self.is_named_param() {
1551 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1553 let pat = self.parse_fn_param_pat()?;
1554 if let Err(mut err) = self.expect(&token::Colon) {
1555 return if let Some(ident) =
1556 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1559 Ok(dummy_arg(ident))
1565 self.eat_incorrect_doc_comment_for_param_type();
1566 (pat, self.parse_ty_for_param()?)
1568 debug!("parse_param_general ident_to_pat");
1569 let parser_snapshot_before_ty = self.clone();
1570 self.eat_incorrect_doc_comment_for_param_type();
1571 let mut ty = self.parse_ty_for_param();
1573 && self.token != token::Comma
1574 && self.token != token::CloseDelim(token::Paren)
1576 // This wasn't actually a type, but a pattern looking like a type,
1577 // so we are going to rollback and re-parse for recovery.
1578 ty = self.unexpected();
1582 let ident = Ident::new(kw::Invalid, self.prev_span);
1583 let bm = BindingMode::ByValue(Mutability::Not);
1584 let pat = self.mk_pat_ident(ty.span, bm, ident);
1587 // If this is a C-variadic argument and we hit an error, return the error.
1588 Err(err) if self.token == token::DotDotDot => return Err(err),
1589 // Recover from attempting to parse the argument as a type without pattern.
1592 mem::replace(self, parser_snapshot_before_ty);
1593 self.recover_arg_parse()?
1598 let span = lo.to(self.token.span);
1601 attrs: attrs.into(),
1602 id: ast::DUMMY_NODE_ID,
1603 is_placeholder: false,
1610 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1611 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1612 // Extract an identifier *after* having confirmed that the token is one.
1613 let expect_self_ident = |this: &mut Self| {
1614 match this.token.kind {
1615 // Preserve hygienic context.
1616 token::Ident(name, _) => {
1617 let span = this.token.span;
1619 Ident::new(name, span)
1621 _ => unreachable!(),
1624 // Is `self` `n` tokens ahead?
1625 let is_isolated_self = |this: &Self, n| {
1626 this.is_keyword_ahead(n, &[kw::SelfLower])
1627 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1629 // Is `mut self` `n` tokens ahead?
1630 let is_isolated_mut_self =
1631 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1632 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1633 let parse_self_possibly_typed = |this: &mut Self, m| {
1634 let eself_ident = expect_self_ident(this);
1635 let eself_hi = this.prev_span;
1636 let eself = if this.eat(&token::Colon) {
1637 SelfKind::Explicit(this.parse_ty()?, m)
1641 Ok((eself, eself_ident, eself_hi))
1643 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1644 let recover_self_ptr = |this: &mut Self| {
1645 let msg = "cannot pass `self` by raw pointer";
1646 let span = this.token.span;
1647 this.struct_span_err(span, msg).span_label(span, msg).emit();
1649 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1652 // Parse optional `self` parameter of a method.
1653 // Only a limited set of initial token sequences is considered `self` parameters; anything
1654 // else is parsed as a normal function parameter list, so some lookahead is required.
1655 let eself_lo = self.token.span;
1656 let (eself, eself_ident, eself_hi) = match self.token.kind {
1657 token::BinOp(token::And) => {
1658 let eself = if is_isolated_self(self, 1) {
1661 SelfKind::Region(None, Mutability::Not)
1662 } else if is_isolated_mut_self(self, 1) {
1666 SelfKind::Region(None, Mutability::Mut)
1667 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1670 let lt = self.expect_lifetime();
1671 SelfKind::Region(Some(lt), Mutability::Not)
1672 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1675 let lt = self.expect_lifetime();
1677 SelfKind::Region(Some(lt), Mutability::Mut)
1682 (eself, expect_self_ident(self), self.prev_span)
1685 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1687 recover_self_ptr(self)?
1689 // `*mut self` and `*const self`
1690 token::BinOp(token::Star)
1691 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1695 recover_self_ptr(self)?
1697 // `self` and `self: TYPE`
1698 token::Ident(..) if is_isolated_self(self, 0) => {
1699 parse_self_possibly_typed(self, Mutability::Not)?
1701 // `mut self` and `mut self: TYPE`
1702 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1704 parse_self_possibly_typed(self, Mutability::Mut)?
1706 _ => return Ok(None),
1709 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1710 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1713 fn is_named_param(&self) -> bool {
1714 let offset = match self.token.kind {
1715 token::Interpolated(ref nt) => match **nt {
1716 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1719 token::BinOp(token::And) | token::AndAnd => 1,
1720 _ if self.token.is_keyword(kw::Mut) => 1,
1724 self.look_ahead(offset, |t| t.is_ident())
1725 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1728 fn recover_first_param(&mut self) -> &'static str {
1730 .parse_outer_attributes()
1731 .and_then(|_| self.parse_self_param())
1732 .map_err(|mut e| e.cancel())
1734 Ok(Some(_)) => "method",