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, DiagnosticBuilder, PResult, StashKey};
9 use rustc_span::source_map::{self, Span};
10 use rustc_span::symbol::{kw, sym, Symbol};
11 use rustc_span::BytePos;
12 use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
13 use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind};
14 use syntax::ast::{Async, Const, Defaultness, IsAuto, PathSegment, Unsafe};
15 use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind};
16 use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
17 use syntax::ast::{FnHeader, ForeignItem, ForeignItemKind, Mutability, Visibility, VisibilityKind};
20 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
25 pub(super) type ItemInfo = (Ident, ItemKind);
28 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
29 let attrs = self.parse_outer_attributes()?;
30 self.parse_item_(attrs, true, false)
33 pub(super) fn parse_item_(
35 attrs: Vec<Attribute>,
37 attributes_allowed: bool,
38 ) -> PResult<'a, Option<P<Item>>> {
39 let mut unclosed_delims = vec![];
40 let (ret, tokens) = self.collect_tokens(|this| {
41 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
42 unclosed_delims.append(&mut this.unclosed_delims);
45 self.unclosed_delims.append(&mut unclosed_delims);
47 // Once we've parsed an item and recorded the tokens we got while
48 // parsing we may want to store `tokens` into the item we're about to
49 // return. Note, though, that we specifically didn't capture tokens
50 // related to outer attributes. The `tokens` field here may later be
51 // used with procedural macros to convert this item back into a token
52 // stream, but during expansion we may be removing attributes as we go
55 // If we've got inner attributes then the `tokens` we've got above holds
56 // these inner attributes. If an inner attribute is expanded we won't
57 // actually remove it from the token stream, so we'll just keep yielding
58 // it (bad!). To work around this case for now we just avoid recording
59 // `tokens` if we detect any inner attributes. This should help keep
60 // expansion correct, but we should fix this bug one day!
63 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
64 i.tokens = Some(tokens);
71 /// Parses one of the items allowed by the flags.
72 fn parse_item_implementation(
74 mut attrs: Vec<Attribute>,
76 attributes_allowed: bool,
77 ) -> PResult<'a, Option<P<Item>>> {
78 maybe_whole!(self, NtItem, |item| {
80 mem::swap(&mut item.attrs, &mut attrs);
81 item.attrs.extend(attrs);
85 let lo = self.token.span;
86 let vis = self.parse_visibility(FollowedByType::No)?;
88 if let Some((ident, kind)) = self.parse_item_kind(&mut attrs, macros_allowed, lo, &vis)? {
89 return Ok(Some(P(self.mk_item(lo, ident, kind, vis, attrs))));
92 // FAILURE TO PARSE ITEM
94 VisibilityKind::Inherited => {}
96 self.struct_span_err(vis.span, "unmatched visibility `pub`")
97 .span_label(vis.span, "the unmatched visibility")
98 .help("you likely meant to define an item, e.g., `pub fn foo() {}`")
103 if !attributes_allowed && !attrs.is_empty() {
104 self.expected_item_err(&attrs)?;
109 /// Parses one of the items allowed by the flags.
112 attrs: &mut Vec<Attribute>,
113 macros_allowed: bool,
116 ) -> PResult<'a, Option<ItemInfo>> {
117 let info = if self.eat_keyword(kw::Use) {
119 let tree = self.parse_use_tree()?;
121 (Ident::invalid(), ItemKind::Use(P(tree)))
122 } else if self.check_fn_front_matter() {
124 let (ident, sig, generics, body) = self.parse_fn(&mut false, attrs, |_| true)?;
125 (ident, ItemKind::Fn(sig, generics, body))
126 } else if self.eat_keyword(kw::Extern) {
127 if self.eat_keyword(kw::Crate) {
129 self.parse_item_extern_crate()?
132 self.parse_item_foreign_mod(attrs)?
134 } else if self.is_static_global() {
136 self.bump(); // `static`
137 let m = self.parse_mutability();
138 self.parse_item_const(Some(m))?
139 } else if let Const::Yes(const_span) = self.parse_constness() {
141 if self.eat_keyword(kw::Mut) {
142 let prev_span = self.prev_span;
143 self.struct_span_err(prev_span, "const globals cannot be mutable")
144 .span_label(prev_span, "cannot be mutable")
147 "you might want to declare a static instead",
149 Applicability::MaybeIncorrect,
154 self.parse_item_const(None)?
155 } else if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
158 let unsafety = self.parse_unsafety();
159 self.parse_item_trait(attrs, lo, unsafety)?
160 } else if self.check_keyword(kw::Impl)
161 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
162 || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
165 let defaultness = self.parse_defaultness();
166 let unsafety = self.parse_unsafety();
167 self.expect_keyword(kw::Impl)?;
168 self.parse_item_impl(attrs, unsafety, defaultness)?
169 } else if self.eat_keyword(kw::Mod) {
171 self.parse_item_mod(attrs)?
172 } else if self.eat_keyword(kw::Type) {
174 let (ident, ty, generics) = self.parse_type_alias()?;
175 (ident, ItemKind::TyAlias(ty, generics))
176 } else if self.eat_keyword(kw::Enum) {
178 self.parse_item_enum()?
179 } else if self.check_keyword(kw::Trait)
180 || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]))
183 self.parse_item_trait(attrs, lo, Unsafe::No)?
184 } else if self.eat_keyword(kw::Struct) {
186 self.parse_item_struct()?
187 } else if self.is_union_item() {
189 self.bump(); // `union`
190 self.parse_item_union()?
191 } else if self.eat_keyword(kw::Macro) {
193 self.parse_item_decl_macro(lo)?
194 } else if self.is_macro_rules_item() {
196 self.parse_item_macro_rules(vis)?
197 } else if vis.node.is_pub()
198 && self.check_ident()
199 && self.look_ahead(1, |t| *t != token::Not)
201 self.recover_missing_kw_before_item()?;
203 } else if macros_allowed && self.token.is_path_start() {
204 // MACRO INVOCATION ITEM
205 self.parse_item_macro(vis)?
212 /// Recover on encountering a struct or method definition where the user
213 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
214 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
215 // Space between `pub` keyword and the identifier
218 // ^^^ `sp` points here
219 let sp = self.prev_span.between(self.token.span);
220 let full_sp = self.prev_span.to(self.token.span);
221 let ident_sp = self.token.span;
222 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
223 // possible public struct definition where `struct` was forgotten
224 let ident = self.parse_ident().unwrap();
225 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
226 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
227 err.span_suggestion_short(
231 Applicability::MaybeIncorrect, // speculative
234 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
235 let ident = self.parse_ident().unwrap();
237 let kw_name = self.recover_first_param();
238 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
239 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
240 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
242 ("fn", kw_name, false)
243 } else if self.check(&token::OpenDelim(token::Brace)) {
245 ("fn", kw_name, false)
246 } else if self.check(&token::Colon) {
250 ("fn` or `struct", "function or struct", true)
253 let msg = format!("missing `{}` for {} definition", kw, kw_name);
254 let mut err = self.struct_span_err(sp, &msg);
256 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
258 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
259 err.span_suggestion_short(
263 Applicability::MachineApplicable,
266 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
269 "if you meant to call a macro, try",
270 format!("{}!", snippet),
271 // this is the `ambiguous` conditional branch
272 Applicability::MaybeIncorrect,
276 "if you meant to call a macro, remove the `pub` \
277 and add a trailing `!` after the identifier",
282 } else if self.look_ahead(1, |t| *t == token::Lt) {
283 let ident = self.parse_ident().unwrap();
284 self.eat_to_tokens(&[&token::Gt]);
286 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
287 ("fn", self.recover_first_param(), false)
288 } else if self.check(&token::OpenDelim(token::Brace)) {
289 ("struct", "struct", false)
291 ("fn` or `struct", "function or struct", true)
293 let msg = format!("missing `{}` for {} definition", kw, kw_name);
294 let mut err = self.struct_span_err(sp, &msg);
296 err.span_suggestion_short(
298 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
300 Applicability::MachineApplicable,
309 /// Parses an item macro, e.g., `item!();`.
310 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
311 self.complain_if_pub_macro(&vis.node, vis.span);
314 let path = self.parse_path(PathStyle::Mod)?;
315 self.expect(&token::Not)?;
316 let args = self.parse_mac_args()?;
317 if args.need_semicolon() && !self.eat(&token::Semi) {
318 self.report_invalid_macro_expansion_item();
321 let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };
322 Ok((Ident::invalid(), ItemKind::Mac(mac)))
325 /// Emits an expected-item-after-attributes error.
326 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
327 let message = match attrs.last() {
328 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => {
329 "expected item after doc comment"
331 _ => "expected item after attributes",
334 let mut err = self.struct_span_err(self.prev_span, message);
335 if attrs.last().unwrap().is_doc_comment() {
336 err.span_label(self.prev_span, "this doc comment doesn't document anything");
341 pub(super) fn is_async_fn(&self) -> bool {
342 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
345 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
346 fn parse_assoc_macro_invoc(
349 vis: Option<&Visibility>,
351 ) -> PResult<'a, Option<Mac>> {
352 if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) {
353 let prev_span = self.prev_span;
354 let path = self.parse_path(PathStyle::Mod)?;
356 if path.segments.len() == 1 {
357 if !self.eat(&token::Not) {
358 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
361 self.expect(&token::Not)?;
364 if let Some(vis) = vis {
365 self.complain_if_pub_macro(&vis.node, prev_span);
370 // eat a matched-delimiter token tree:
371 let args = self.parse_mac_args()?;
372 if args.need_semicolon() {
376 Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription }))
382 fn missing_assoc_item_kind_err(
386 ) -> DiagnosticBuilder<'a> {
387 let expected_kinds = if item_type == "extern" {
388 "missing `fn`, `type`, or `static`"
390 "missing `fn`, `type`, or `const`"
393 // Given this code `path(`, it seems like this is not
394 // setting the visibility of a macro invocation, but rather
395 // a mistyped method declaration.
396 // Create a diagnostic pointing out that `fn` is missing.
398 // x | pub path(&self) {
399 // | ^ missing `fn`, `type`, or `const`
401 // ^^ `sp` below will point to this
402 let sp = prev_span.between(self.prev_span);
404 .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type));
405 err.span_label(sp, expected_kinds);
409 /// Parses an implementation item, `impl` keyword is already parsed.
412 /// impl<'a, T> TYPE { /* impl items */ }
413 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
414 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
415 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
418 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
420 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
421 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
425 attrs: &mut Vec<Attribute>,
427 defaultness: Defaultness,
428 ) -> PResult<'a, ItemInfo> {
429 // First, parse generic parameters if necessary.
430 let mut generics = if self.choose_generics_over_qpath() {
431 self.parse_generics()?
433 let mut generics = Generics::default();
435 // /\ this is where `generics.span` should point when there are no type params.
436 generics.span = self.prev_span.shrink_to_hi();
440 let constness = self.parse_constness();
441 if let Const::Yes(span) = constness {
442 self.sess.gated_spans.gate(sym::const_trait_impl, span);
445 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
446 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
448 ast::ImplPolarity::Negative
450 ast::ImplPolarity::Positive
453 // Parse both types and traits as a type, then reinterpret if necessary.
454 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
455 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
457 let span = self.prev_span.between(self.token.span);
458 self.struct_span_err(span, "missing trait in a trait impl").emit();
459 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
464 // If `for` is missing we try to recover.
465 let has_for = self.eat_keyword(kw::For);
466 let missing_for_span = self.prev_span.between(self.token.span);
468 let ty_second = if self.token == token::DotDot {
469 // We need to report this error after `cfg` expansion for compatibility reasons
470 self.bump(); // `..`, do not add it to expected tokens
471 Some(self.mk_ty(self.prev_span, TyKind::Err))
472 } else if has_for || self.token.can_begin_type() {
473 Some(self.parse_ty()?)
478 generics.where_clause = self.parse_where_clause()?;
480 let impl_items = self.parse_item_list(attrs, |p, at_end| p.parse_impl_item(at_end))?;
482 let item_kind = match ty_second {
484 // impl Trait for Type
486 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
487 .span_suggestion_short(
491 Applicability::MachineApplicable,
496 let ty_first = ty_first.into_inner();
497 let path = match ty_first.kind {
498 // This notably includes paths passed through `ty` macro fragments (#46438).
499 TyKind::Path(None, path) => path,
501 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
502 err_path(ty_first.span)
505 let trait_ref = TraitRef { path, ref_id: ty_first.id };
513 of_trait: Some(trait_ref),
533 Ok((Ident::invalid(), item_kind))
536 fn parse_item_list<T>(
538 attrs: &mut Vec<Attribute>,
539 mut parse_item: impl FnMut(&mut Parser<'a>, &mut bool) -> PResult<'a, T>,
540 ) -> PResult<'a, Vec<T>> {
541 self.expect(&token::OpenDelim(token::Brace))?;
542 attrs.append(&mut self.parse_inner_attributes()?);
544 let mut items = Vec::new();
545 while !self.eat(&token::CloseDelim(token::Brace)) {
546 if self.recover_doc_comment_before_brace() {
549 let mut at_end = false;
550 match parse_item(self, &mut at_end) {
551 Ok(item) => items.push(item),
555 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
564 /// Recover on a doc comment before `}`.
565 fn recover_doc_comment_before_brace(&mut self) -> bool {
566 if let token::DocComment(_) = self.token.kind {
567 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
572 "found a documentation comment that doesn't document anything",
574 .span_label(self.token.span, "this doc comment doesn't document anything")
576 "doc comments must come before what they document, maybe a \
577 comment was intended with `//`?",
587 /// Parses defaultness (i.e., `default` or nothing).
588 fn parse_defaultness(&mut self) -> Defaultness {
589 // `pub` is included for better error messages
590 if self.check_keyword(kw::Default)
591 && self.is_keyword_ahead(
605 self.bump(); // `default`
612 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
615 attrs: &mut Vec<Attribute>,
618 ) -> PResult<'a, ItemInfo> {
619 // Parse optional `auto` prefix.
620 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
622 self.expect_keyword(kw::Trait)?;
623 let ident = self.parse_ident()?;
624 let mut tps = self.parse_generics()?;
626 // Parse optional colon and supertrait bounds.
627 let had_colon = self.eat(&token::Colon);
628 let span_at_colon = self.prev_span;
630 if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() };
632 let span_before_eq = self.prev_span;
633 if self.eat(&token::Eq) {
634 // It's a trait alias.
636 let span = span_at_colon.to(span_before_eq);
637 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
640 let bounds = self.parse_generic_bounds(None)?;
641 tps.where_clause = self.parse_where_clause()?;
644 let whole_span = lo.to(self.prev_span);
645 if is_auto == IsAuto::Yes {
646 let msg = "trait aliases cannot be `auto`";
647 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
649 if let Unsafe::Yes(_) = unsafety {
650 let msg = "trait aliases cannot be `unsafe`";
651 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
654 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
656 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
658 // It's a normal trait.
659 tps.where_clause = self.parse_where_clause()?;
660 let items = self.parse_item_list(attrs, |p, at_end| p.parse_trait_item(at_end))?;
661 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
665 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
666 maybe_whole!(self, NtImplItem, |x| x);
667 self.parse_assoc_item(at_end, |_| true)
670 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, P<AssocItem>> {
671 maybe_whole!(self, NtTraitItem, |x| x);
672 // This is somewhat dubious; We don't want to allow
673 // param names to be left off if there is a definition...
675 // We don't allow param names to be left off in edition 2018.
676 self.parse_assoc_item(at_end, |t| t.span.rust_2018())
679 /// Parses associated items.
683 req_name: fn(&token::Token) -> bool,
684 ) -> PResult<'a, P<AssocItem>> {
685 let attrs = self.parse_outer_attributes()?;
686 let mut unclosed_delims = vec![];
687 let (mut item, tokens) = self.collect_tokens(|this| {
688 let item = this.parse_assoc_item_(at_end, attrs, req_name);
689 unclosed_delims.append(&mut this.unclosed_delims);
692 self.unclosed_delims.append(&mut unclosed_delims);
693 // See `parse_item` for why this clause is here.
694 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
695 item.tokens = Some(tokens);
700 fn parse_assoc_item_(
703 mut attrs: Vec<Attribute>,
704 req_name: fn(&token::Token) -> bool,
705 ) -> PResult<'a, AssocItem> {
706 let lo = self.token.span;
707 let vis = self.parse_visibility(FollowedByType::No)?;
708 let defaultness = self.parse_defaultness();
710 let (ident, kind, generics) = if self.eat_keyword(kw::Type) {
711 self.parse_assoc_ty()?
712 } else if self.check_fn_front_matter() {
713 let (ident, sig, generics, body) = self.parse_fn(at_end, &mut attrs, req_name)?;
714 (ident, AssocItemKind::Fn(sig, body), generics)
715 } else if let Some(mac) = self.parse_assoc_macro_invoc("associated", Some(&vis), at_end)? {
716 (Ident::invalid(), AssocItemKind::Macro(mac), Generics::default())
718 self.parse_assoc_const()?
721 let span = lo.to(self.prev_span);
722 let id = DUMMY_NODE_ID;
723 Ok(AssocItem { id, span, ident, attrs, vis, defaultness, generics, kind, tokens: None })
726 /// This parses the grammar:
728 /// AssocConst = "const" Ident ":" Ty "=" Expr ";"
729 fn parse_assoc_const(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
730 self.expect_keyword(kw::Const)?;
731 let ident = self.parse_ident()?;
732 self.expect(&token::Colon)?;
733 let ty = self.parse_ty()?;
734 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
736 Ok((ident, AssocItemKind::Const(ty, expr), Generics::default()))
739 /// Parses the following grammar:
741 /// AssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
742 fn parse_assoc_ty(&mut self) -> PResult<'a, (Ident, AssocItemKind, Generics)> {
743 let ident = self.parse_ident()?;
744 let mut generics = self.parse_generics()?;
746 // Parse optional colon and param bounds.
748 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
749 generics.where_clause = self.parse_where_clause()?;
751 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
754 Ok((ident, AssocItemKind::TyAlias(bounds, default), generics))
757 /// Parses a `UseTree`.
760 /// USE_TREE = [`::`] `*` |
761 /// [`::`] `{` USE_TREE_LIST `}` |
763 /// PATH `::` `{` USE_TREE_LIST `}` |
764 /// PATH [`as` IDENT]
766 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
767 let lo = self.token.span;
769 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
770 let kind = if self.check(&token::OpenDelim(token::Brace))
771 || self.check(&token::BinOp(token::Star))
772 || self.is_import_coupler()
774 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
775 let mod_sep_ctxt = self.token.span.ctxt();
776 if self.eat(&token::ModSep) {
779 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
782 self.parse_use_tree_glob_or_nested()?
784 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
785 prefix = self.parse_path(PathStyle::Mod)?;
787 if self.eat(&token::ModSep) {
788 self.parse_use_tree_glob_or_nested()?
790 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
794 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
797 /// Parses `*` or `{...}`.
798 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
799 Ok(if self.eat(&token::BinOp(token::Star)) {
802 UseTreeKind::Nested(self.parse_use_tree_list()?)
806 /// Parses a `UseTreeKind::Nested(list)`.
809 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
811 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
812 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
816 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
817 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
820 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
821 match self.token.kind {
822 token::Ident(name, false) if name == kw::Underscore => {
823 let span = self.token.span;
825 Ok(Ident::new(name, span))
827 _ => self.parse_ident(),
831 /// Parses `extern crate` links.
836 /// extern crate foo;
837 /// extern crate bar as foo;
839 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
840 // Accept `extern crate name-like-this` for better diagnostics
841 let orig_name = self.parse_crate_name_with_dashes()?;
842 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
843 (rename, Some(orig_name.name))
848 Ok((item_name, ItemKind::ExternCrate(orig_name)))
851 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
852 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
853 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
855 let mut ident = if self.token.is_keyword(kw::SelfLower) {
856 self.parse_path_segment_ident()
860 let mut idents = vec![];
861 let mut replacement = vec![];
862 let mut fixed_crate_name = false;
863 // Accept `extern crate name-like-this` for better diagnostics.
864 let dash = token::BinOp(token::BinOpToken::Minus);
865 if self.token == dash {
866 // Do not include `-` as part of the expected tokens list.
867 while self.eat(&dash) {
868 fixed_crate_name = true;
869 replacement.push((self.prev_span, "_".to_string()));
870 idents.push(self.parse_ident()?);
873 if fixed_crate_name {
874 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
875 let mut fixed_name = format!("{}", ident.name);
877 fixed_name.push_str(&format!("_{}", part.name));
879 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
881 self.struct_span_err(fixed_name_sp, error_msg)
882 .span_label(fixed_name_sp, "dash-separated idents are not valid")
883 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
889 /// Parses `extern` for foreign ABIs modules.
891 /// `extern` is expected to have been consumed before calling this method.
895 /// ```ignore (only-for-syntax-highlight)
899 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
900 let abi = self.parse_abi(); // ABI?
901 let items = self.parse_item_list(attrs, |p, at_end| p.parse_foreign_item(at_end))?;
902 let module = ast::ForeignMod { abi, items };
903 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
906 /// Parses a foreign item (one in an `extern { ... }` block).
907 pub fn parse_foreign_item(&mut self, at_end: &mut bool) -> PResult<'a, P<ForeignItem>> {
908 maybe_whole!(self, NtForeignItem, |ni| ni);
910 let mut attrs = self.parse_outer_attributes()?;
911 let lo = self.token.span;
912 let vis = self.parse_visibility(FollowedByType::No)?;
914 let (ident, kind) = if self.check_keyword(kw::Type) {
916 self.parse_item_foreign_type()?
917 } else if self.check_fn_front_matter() {
918 // FOREIGN FUNCTION ITEM
919 let (ident, sig, generics, body) = self.parse_fn(at_end, &mut attrs, |_| true)?;
920 (ident, ForeignItemKind::Fn(sig, generics, body))
921 } else if self.is_static_global() {
922 // FOREIGN STATIC ITEM
923 self.bump(); // `static`
924 self.parse_item_foreign_static()?
925 } else if self.token.is_keyword(kw::Const) {
926 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
927 self.bump(); // `const`
928 self.struct_span_err(self.prev_span, "extern items cannot be `const`")
931 "try using a static value",
933 Applicability::MachineApplicable,
936 self.parse_item_foreign_static()?
937 } else if let Some(mac) = self.parse_assoc_macro_invoc("extern", Some(&vis), at_end)? {
938 (Ident::invalid(), ForeignItemKind::Macro(mac))
940 if !attrs.is_empty() {
941 self.expected_item_err(&attrs)?;
945 Ok(P(self.mk_item(lo, ident, kind, vis, attrs)))
948 /// Parses a static item from a foreign module.
949 /// Assumes that the `static` keyword is already parsed.
950 fn parse_item_foreign_static(&mut self) -> PResult<'a, (Ident, ForeignItemKind)> {
951 let mutbl = self.parse_mutability();
952 let ident = self.parse_ident()?;
953 self.expect(&token::Colon)?;
954 let ty = self.parse_ty()?;
956 Ok((ident, ForeignItemKind::Static(ty, mutbl)))
959 /// Parses a type from a foreign module.
960 fn parse_item_foreign_type(&mut self) -> PResult<'a, (Ident, ForeignItemKind)> {
961 self.expect_keyword(kw::Type)?;
962 let ident = self.parse_ident()?;
964 Ok((ident, ForeignItemKind::Ty))
967 fn is_static_global(&mut self) -> bool {
968 if self.check_keyword(kw::Static) {
969 // Check if this could be a closure.
970 !self.look_ahead(1, |token| {
971 if token.is_keyword(kw::Move) {
975 token::BinOp(token::Or) | token::OrOr => true,
984 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
985 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
987 /// When `m` is `"const"`, `$ident` may also be `"_"`.
988 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
989 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
991 // Parse the type of a `const` or `static mut?` item.
992 // That is, the `":" $ty` fragment.
993 let ty = if self.token == token::Eq {
994 self.recover_missing_const_type(id, m)
996 // Not `=` so expect `":"" $ty` as usual.
997 self.expect(&token::Colon)?;
1001 self.expect(&token::Eq)?;
1002 let e = self.parse_expr()?;
1003 self.expect_semi()?;
1004 let item = match m {
1005 Some(m) => ItemKind::Static(ty, m, e),
1006 None => ItemKind::Const(ty, e),
1011 /// We were supposed to parse `:` but instead, we're already at `=`.
1012 /// This means that the type is missing.
1013 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1014 // Construct the error and stash it away with the hope
1015 // that typeck will later enrich the error with a type.
1016 let kind = match m {
1017 Some(Mutability::Mut) => "static mut",
1018 Some(Mutability::Not) => "static",
1021 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1022 err.span_suggestion(
1024 "provide a type for the item",
1025 format!("{}: <type>", id),
1026 Applicability::HasPlaceholders,
1028 err.stash(id.span, StashKey::ItemNoType);
1030 // The user intended that the type be inferred,
1031 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1032 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1035 /// Parses the grammar:
1036 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1037 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1038 let ident = self.parse_ident()?;
1039 let mut tps = self.parse_generics()?;
1040 tps.where_clause = self.parse_where_clause()?;
1041 self.expect(&token::Eq)?;
1042 let ty = self.parse_ty()?;
1043 self.expect_semi()?;
1044 Ok((ident, ty, tps))
1047 /// Parses an enum declaration.
1048 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1049 let id = self.parse_ident()?;
1050 let mut generics = self.parse_generics()?;
1051 generics.where_clause = self.parse_where_clause()?;
1054 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1055 self.recover_stmt();
1059 let enum_definition =
1060 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1061 Ok((id, ItemKind::Enum(enum_definition, generics)))
1064 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1065 let variant_attrs = self.parse_outer_attributes()?;
1066 let vlo = self.token.span;
1068 let vis = self.parse_visibility(FollowedByType::No)?;
1069 if !self.recover_nested_adt_item(kw::Enum)? {
1072 let ident = self.parse_ident()?;
1074 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1075 // Parse a struct variant.
1076 let (fields, recovered) = self.parse_record_struct_body()?;
1077 VariantData::Struct(fields, recovered)
1078 } else if self.check(&token::OpenDelim(token::Paren)) {
1079 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1081 VariantData::Unit(DUMMY_NODE_ID)
1085 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1087 let vr = ast::Variant {
1091 attrs: variant_attrs,
1094 span: vlo.to(self.prev_span),
1095 is_placeholder: false,
1101 /// Parses `struct Foo { ... }`.
1102 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1103 let class_name = self.parse_ident()?;
1105 let mut generics = self.parse_generics()?;
1107 // There is a special case worth noting here, as reported in issue #17904.
1108 // If we are parsing a tuple struct it is the case that the where clause
1109 // should follow the field list. Like so:
1111 // struct Foo<T>(T) where T: Copy;
1113 // If we are parsing a normal record-style struct it is the case
1114 // that the where clause comes before the body, and after the generics.
1115 // So if we look ahead and see a brace or a where-clause we begin
1116 // parsing a record style struct.
1118 // Otherwise if we look ahead and see a paren we parse a tuple-style
1121 let vdata = if self.token.is_keyword(kw::Where) {
1122 generics.where_clause = self.parse_where_clause()?;
1123 if self.eat(&token::Semi) {
1124 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1125 VariantData::Unit(DUMMY_NODE_ID)
1127 // If we see: `struct Foo<T> where T: Copy { ... }`
1128 let (fields, recovered) = self.parse_record_struct_body()?;
1129 VariantData::Struct(fields, recovered)
1131 // No `where` so: `struct Foo<T>;`
1132 } else if self.eat(&token::Semi) {
1133 VariantData::Unit(DUMMY_NODE_ID)
1134 // Record-style struct definition
1135 } else if self.token == token::OpenDelim(token::Brace) {
1136 let (fields, recovered) = self.parse_record_struct_body()?;
1137 VariantData::Struct(fields, recovered)
1138 // Tuple-style struct definition with optional where-clause.
1139 } else if self.token == token::OpenDelim(token::Paren) {
1140 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1141 generics.where_clause = self.parse_where_clause()?;
1142 self.expect_semi()?;
1145 let token_str = super::token_descr(&self.token);
1147 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1150 let mut err = self.struct_span_err(self.token.span, msg);
1151 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1155 Ok((class_name, ItemKind::Struct(vdata, generics)))
1158 /// Parses `union Foo { ... }`.
1159 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1160 let class_name = self.parse_ident()?;
1162 let mut generics = self.parse_generics()?;
1164 let vdata = if self.token.is_keyword(kw::Where) {
1165 generics.where_clause = self.parse_where_clause()?;
1166 let (fields, recovered) = self.parse_record_struct_body()?;
1167 VariantData::Struct(fields, recovered)
1168 } else if self.token == token::OpenDelim(token::Brace) {
1169 let (fields, recovered) = self.parse_record_struct_body()?;
1170 VariantData::Struct(fields, recovered)
1172 let token_str = super::token_descr(&self.token);
1173 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1174 let mut err = self.struct_span_err(self.token.span, msg);
1175 err.span_label(self.token.span, "expected `where` or `{` after union name");
1179 Ok((class_name, ItemKind::Union(vdata, generics)))
1182 pub(super) fn is_union_item(&self) -> bool {
1183 self.token.is_keyword(kw::Union)
1184 && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1187 fn parse_record_struct_body(
1189 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1190 let mut fields = Vec::new();
1191 let mut recovered = false;
1192 if self.eat(&token::OpenDelim(token::Brace)) {
1193 while self.token != token::CloseDelim(token::Brace) {
1194 let field = self.parse_struct_decl_field().map_err(|e| {
1195 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1200 Ok(field) => fields.push(field),
1207 self.eat(&token::CloseDelim(token::Brace));
1209 let token_str = super::token_descr(&self.token);
1210 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1211 let mut err = self.struct_span_err(self.token.span, msg);
1212 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1216 Ok((fields, recovered))
1219 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1220 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1221 // Unit like structs are handled in parse_item_struct function
1222 self.parse_paren_comma_seq(|p| {
1223 let attrs = p.parse_outer_attributes()?;
1224 let lo = p.token.span;
1225 let vis = p.parse_visibility(FollowedByType::Yes)?;
1226 let ty = p.parse_ty()?;
1228 span: lo.to(ty.span),
1234 is_placeholder: false,
1240 /// Parses an element of a struct declaration.
1241 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1242 let attrs = self.parse_outer_attributes()?;
1243 let lo = self.token.span;
1244 let vis = self.parse_visibility(FollowedByType::No)?;
1245 self.parse_single_struct_field(lo, vis, attrs)
1248 /// Parses a structure field declaration.
1249 fn parse_single_struct_field(
1253 attrs: Vec<Attribute>,
1254 ) -> PResult<'a, StructField> {
1255 let mut seen_comma: bool = false;
1256 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1257 if self.token == token::Comma {
1260 match self.token.kind {
1264 token::CloseDelim(token::Brace) => {}
1265 token::DocComment(_) => {
1266 let previous_span = self.prev_span;
1267 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1268 self.bump(); // consume the doc comment
1269 let comma_after_doc_seen = self.eat(&token::Comma);
1270 // `seen_comma` is always false, because we are inside doc block
1271 // condition is here to make code more readable
1272 if seen_comma == false && comma_after_doc_seen == true {
1275 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1278 if seen_comma == false {
1279 let sp = self.sess.source_map().next_point(previous_span);
1280 err.span_suggestion(
1282 "missing comma here",
1284 Applicability::MachineApplicable,
1291 let sp = self.prev_span.shrink_to_hi();
1292 let mut err = self.struct_span_err(
1294 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1296 if self.token.is_ident() {
1297 // This is likely another field; emit the diagnostic and keep going
1298 err.span_suggestion(
1300 "try adding a comma",
1302 Applicability::MachineApplicable,
1313 /// Parses a structure field.
1314 fn parse_name_and_ty(
1318 attrs: Vec<Attribute>,
1319 ) -> PResult<'a, StructField> {
1320 let name = self.parse_ident()?;
1321 self.expect(&token::Colon)?;
1322 let ty = self.parse_ty()?;
1324 span: lo.to(self.prev_span),
1330 is_placeholder: false,
1334 /// Parses a declarative macro 2.0 definition.
1335 /// The `macro` keyword has already been parsed.
1336 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1337 let ident = self.parse_ident()?;
1338 let body = if self.check(&token::OpenDelim(token::Brace)) {
1339 self.parse_mac_args()?
1340 } else if self.check(&token::OpenDelim(token::Paren)) {
1341 let params = self.parse_token_tree();
1342 let pspan = params.span();
1343 let body = if self.check(&token::OpenDelim(token::Brace)) {
1344 self.parse_token_tree()
1346 return self.unexpected();
1348 let bspan = body.span();
1349 let tokens = TokenStream::new(vec![
1351 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1354 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1355 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1357 return self.unexpected();
1360 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_span));
1361 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
1364 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1365 pub(super) fn is_macro_rules_item(&mut self) -> bool {
1366 self.check_keyword(sym::macro_rules)
1367 && self.look_ahead(1, |t| *t == token::Not)
1368 && self.look_ahead(2, |t| t.is_ident())
1371 /// Parses a legacy `macro_rules! foo { ... }` declarative macro.
1372 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1373 self.complain_if_pub_macro(&vis.node, vis.span);
1374 self.expect_keyword(sym::macro_rules)?; // `macro_rules`
1375 self.expect(&token::Not)?; // `!`
1377 let ident = self.parse_ident()?;
1378 let body = self.parse_mac_args()?;
1379 if body.need_semicolon() && !self.eat(&token::Semi) {
1380 self.report_invalid_macro_expansion_item();
1383 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
1386 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1388 VisibilityKind::Inherited => {}
1390 let mut err = if self.token.is_keyword(sym::macro_rules) {
1392 self.struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1393 err.span_suggestion(
1395 "try exporting the macro",
1396 "#[macro_export]".to_owned(),
1397 Applicability::MaybeIncorrect, // speculative
1402 self.struct_span_err(sp, "can't qualify macro invocation with `pub`");
1403 err.help("try adjusting the macro to put `pub` inside the invocation");
1411 fn report_invalid_macro_expansion_item(&self) {
1412 let has_close_delim = self
1415 .span_to_snippet(self.prev_span)
1416 .map(|s| s.ends_with(")") || s.ends_with("]"))
1419 let mut err = self.struct_span_err(
1421 "macros that expand to items must be delimited with braces or followed by a semicolon",
1424 // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims
1425 if has_close_delim {
1426 err.multipart_suggestion(
1427 "change the delimiters to curly braces",
1429 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()),
1430 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1432 Applicability::MaybeIncorrect,
1435 err.span_suggestion(
1437 "change the delimiters to curly braces",
1438 " { /* items */ }".to_string(),
1439 Applicability::HasPlaceholders,
1443 err.span_suggestion(
1444 self.prev_span.shrink_to_hi(),
1447 Applicability::MaybeIncorrect,
1452 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1453 /// it is, we try to parse the item and report error about nested types.
1454 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1455 if (self.token.is_keyword(kw::Enum)
1456 || self.token.is_keyword(kw::Struct)
1457 || self.token.is_keyword(kw::Union))
1458 && self.look_ahead(1, |t| t.is_ident())
1460 let kw_token = self.token.clone();
1461 let kw_str = pprust::token_to_string(&kw_token);
1462 let item = self.parse_item()?;
1464 self.struct_span_err(
1466 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1470 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1472 Applicability::MaybeIncorrect,
1475 // We successfully parsed the item but we must inform the caller about nested problem.
1487 attrs: Vec<Attribute>,
1489 let span = lo.to(self.prev_span);
1490 Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None }
1494 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1496 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1497 type ReqName = fn(&token::Token) -> bool;
1499 /// Parsing of functions and methods.
1500 impl<'a> Parser<'a> {
1501 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1505 attrs: &mut Vec<Attribute>,
1507 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1508 let header = self.parse_fn_front_matter()?; // `const ... fn`
1509 let ident = self.parse_ident()?; // `foo`
1510 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1511 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1512 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1513 let body = self.parse_fn_body(at_end, attrs)?; // `;` or `{ ... }`.
1514 Ok((ident, FnSig { header, decl }, generics, body))
1517 /// Parse the "body" of a function.
1518 /// This can either be `;` when there's no body,
1519 /// or e.g. a block when the function is a provided one.
1523 attrs: &mut Vec<Attribute>,
1524 ) -> PResult<'a, Option<P<Block>>> {
1525 let (inner_attrs, body) = match self.token.kind {
1530 token::OpenDelim(token::Brace) => {
1531 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1534 token::Interpolated(ref nt) => match **nt {
1535 token::NtBlock(..) => {
1536 let (attrs, body) = self.parse_inner_attrs_and_block()?;
1539 _ => return self.expected_semi_or_open_brace(),
1541 _ => return self.expected_semi_or_open_brace(),
1543 attrs.extend(inner_attrs);
1548 /// Is the current token the start of an `FnHeader` / not a valid parse?
1549 fn check_fn_front_matter(&mut self) -> bool {
1550 // We use an over-approximation here.
1551 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1552 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1553 self.check_keyword(kw::Fn) // Definitely an `fn`.
1554 // `$qual fn` or `$qual $qual`:
1555 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1556 && self.look_ahead(1, |t| {
1557 // ...qualified and then `fn`, e.g. `const fn`.
1558 t.is_keyword(kw::Fn)
1559 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1560 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1563 || self.check_keyword(kw::Extern)
1564 && self.look_ahead(1, |t| t.can_begin_literal_or_bool())
1565 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1568 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1569 /// up to and including the `fn` keyword. The formal grammar is:
1572 /// Extern = "extern" StringLit ;
1573 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1574 /// FnFrontMatter = FnQual? "fn" ;
1576 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1577 let constness = self.parse_constness();
1578 let asyncness = self.parse_asyncness();
1579 let unsafety = self.parse_unsafety();
1580 let ext = self.parse_extern()?;
1582 if let Async::Yes { span, .. } = asyncness {
1583 self.ban_async_in_2015(span);
1586 if !self.eat_keyword(kw::Fn) {
1587 // It is possible for `expect_one_of` to recover given the contents of
1588 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1589 // account for this.
1590 if !self.expect_one_of(&[], &[])? {
1595 Ok(FnHeader { constness, unsafety, asyncness, ext })
1598 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1599 fn ban_async_in_2015(&self, span: Span) {
1600 if span.rust_2015() {
1601 let diag = self.diagnostic();
1602 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1603 .note("to use `async fn`, switch to Rust 2018")
1604 .help("set `edition = \"2018\"` in `Cargo.toml`")
1605 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1610 /// Parses the parameter list and result type of a function declaration.
1611 pub(super) fn parse_fn_decl(
1614 ret_allow_plus: AllowPlus,
1615 ) -> PResult<'a, P<FnDecl>> {
1617 inputs: self.parse_fn_params(req_name)?,
1618 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1622 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1623 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1624 let mut first_param = true;
1625 // Parse the arguments, starting out with `self` being allowed...
1626 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1627 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1629 let lo = p.prev_span;
1630 // Skip every token until next possible arg or end.
1631 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1632 // Create a placeholder argument for proper arg count (issue #34264).
1633 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_span))))
1635 // ...now that we've parsed the first argument, `self` is no longer allowed.
1636 first_param = false;
1639 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1640 self.deduplicate_recovered_params_names(&mut params);
1644 /// Parses a single function parameter.
1646 /// - `self` is syntactically allowed when `first_param` holds.
1647 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1648 let lo = self.token.span;
1649 let attrs = self.parse_outer_attributes()?;
1651 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1652 if let Some(mut param) = self.parse_self_param()? {
1653 param.attrs = attrs.into();
1654 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1657 let is_name_required = match self.token.kind {
1658 token::DotDotDot => false,
1659 _ => req_name(&self.token),
1661 let (pat, ty) = if is_name_required || self.is_named_param() {
1662 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1664 let pat = self.parse_fn_param_pat()?;
1665 if let Err(mut err) = self.expect(&token::Colon) {
1666 return if let Some(ident) =
1667 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1670 Ok(dummy_arg(ident))
1676 self.eat_incorrect_doc_comment_for_param_type();
1677 (pat, self.parse_ty_for_param()?)
1679 debug!("parse_param_general ident_to_pat");
1680 let parser_snapshot_before_ty = self.clone();
1681 self.eat_incorrect_doc_comment_for_param_type();
1682 let mut ty = self.parse_ty_for_param();
1684 && self.token != token::Comma
1685 && self.token != token::CloseDelim(token::Paren)
1687 // This wasn't actually a type, but a pattern looking like a type,
1688 // so we are going to rollback and re-parse for recovery.
1689 ty = self.unexpected();
1693 let ident = Ident::new(kw::Invalid, self.prev_span);
1694 let bm = BindingMode::ByValue(Mutability::Not);
1695 let pat = self.mk_pat_ident(ty.span, bm, ident);
1698 // If this is a C-variadic argument and we hit an error, return the error.
1699 Err(err) if self.token == token::DotDotDot => return Err(err),
1700 // Recover from attempting to parse the argument as a type without pattern.
1703 mem::replace(self, parser_snapshot_before_ty);
1704 self.recover_arg_parse()?
1709 let span = lo.to(self.token.span);
1712 attrs: attrs.into(),
1713 id: ast::DUMMY_NODE_ID,
1714 is_placeholder: false,
1721 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1722 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1723 // Extract an identifier *after* having confirmed that the token is one.
1724 let expect_self_ident = |this: &mut Self| {
1725 match this.token.kind {
1726 // Preserve hygienic context.
1727 token::Ident(name, _) => {
1728 let span = this.token.span;
1730 Ident::new(name, span)
1732 _ => unreachable!(),
1735 // Is `self` `n` tokens ahead?
1736 let is_isolated_self = |this: &Self, n| {
1737 this.is_keyword_ahead(n, &[kw::SelfLower])
1738 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1740 // Is `mut self` `n` tokens ahead?
1741 let is_isolated_mut_self =
1742 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1743 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1744 let parse_self_possibly_typed = |this: &mut Self, m| {
1745 let eself_ident = expect_self_ident(this);
1746 let eself_hi = this.prev_span;
1747 let eself = if this.eat(&token::Colon) {
1748 SelfKind::Explicit(this.parse_ty()?, m)
1752 Ok((eself, eself_ident, eself_hi))
1754 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1755 let recover_self_ptr = |this: &mut Self| {
1756 let msg = "cannot pass `self` by raw pointer";
1757 let span = this.token.span;
1758 this.struct_span_err(span, msg).span_label(span, msg).emit();
1760 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span))
1763 // Parse optional `self` parameter of a method.
1764 // Only a limited set of initial token sequences is considered `self` parameters; anything
1765 // else is parsed as a normal function parameter list, so some lookahead is required.
1766 let eself_lo = self.token.span;
1767 let (eself, eself_ident, eself_hi) = match self.token.kind {
1768 token::BinOp(token::And) => {
1769 let eself = if is_isolated_self(self, 1) {
1772 SelfKind::Region(None, Mutability::Not)
1773 } else if is_isolated_mut_self(self, 1) {
1777 SelfKind::Region(None, Mutability::Mut)
1778 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1781 let lt = self.expect_lifetime();
1782 SelfKind::Region(Some(lt), Mutability::Not)
1783 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1786 let lt = self.expect_lifetime();
1788 SelfKind::Region(Some(lt), Mutability::Mut)
1793 (eself, expect_self_ident(self), self.prev_span)
1796 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1798 recover_self_ptr(self)?
1800 // `*mut self` and `*const self`
1801 token::BinOp(token::Star)
1802 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1806 recover_self_ptr(self)?
1808 // `self` and `self: TYPE`
1809 token::Ident(..) if is_isolated_self(self, 0) => {
1810 parse_self_possibly_typed(self, Mutability::Not)?
1812 // `mut self` and `mut self: TYPE`
1813 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1815 parse_self_possibly_typed(self, Mutability::Mut)?
1817 _ => return Ok(None),
1820 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1821 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1824 fn is_named_param(&self) -> bool {
1825 let offset = match self.token.kind {
1826 token::Interpolated(ref nt) => match **nt {
1827 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1830 token::BinOp(token::And) | token::AndAnd => 1,
1831 _ if self.token.is_keyword(kw::Mut) => 1,
1835 self.look_ahead(offset, |t| t.is_ident())
1836 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1839 fn recover_first_param(&mut self) -> &'static str {
1841 .parse_outer_attributes()
1842 .and_then(|_| self.parse_self_param())
1843 .map_err(|mut e| e.cancel())
1845 Ok(Some(_)) => "method",