1 use super::{Parser, PathStyle, FollowedByType};
2 use super::diagnostics::{Error, dummy_arg, ConsumeClosingDelim};
4 use crate::maybe_whole;
6 use rustc_errors::{PResult, Applicability, DiagnosticBuilder, StashKey};
7 use rustc_error_codes::*;
8 use syntax::ast::{self, DUMMY_NODE_ID, Ident, Attribute, AttrKind, AttrStyle, AnonConst, Item};
9 use syntax::ast::{ItemKind, ImplItem, ImplItemKind, TraitItem, TraitItemKind, UseTree, UseTreeKind};
10 use syntax::ast::{PathSegment, IsAuto, Constness, IsAsync, Unsafety, Defaultness, Extern, StrLit};
11 use syntax::ast::{Visibility, VisibilityKind, Mutability, FnHeader, ForeignItem, ForeignItemKind};
12 use syntax::ast::{Ty, TyKind, Generics, TraitRef, EnumDef, Variant, VariantData, StructField};
13 use syntax::ast::{Mac, MacArgs, MacDelimiter, Block, BindingMode, FnDecl, FnSig, SelfKind, Param};
14 use syntax::print::pprust;
18 use syntax::tokenstream::{DelimSpan, TokenTree, TokenStream};
19 use syntax::struct_span_err;
20 use syntax_pos::BytePos;
21 use syntax_pos::source_map::{self, respan, Span};
22 use syntax_pos::symbol::{kw, sym, Symbol};
27 pub(super) type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
30 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
31 let attrs = self.parse_outer_attributes()?;
32 self.parse_item_(attrs, true, false)
35 pub(super) fn parse_item_(
37 attrs: Vec<Attribute>,
39 attributes_allowed: bool,
40 ) -> PResult<'a, Option<P<Item>>> {
41 let mut unclosed_delims = vec![];
42 let (ret, tokens) = self.collect_tokens(|this| {
43 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
44 unclosed_delims.append(&mut this.unclosed_delims);
47 self.unclosed_delims.append(&mut unclosed_delims);
49 // Once we've parsed an item and recorded the tokens we got while
50 // parsing we may want to store `tokens` into the item we're about to
51 // return. Note, though, that we specifically didn't capture tokens
52 // related to outer attributes. The `tokens` field here may later be
53 // used with procedural macros to convert this item back into a token
54 // stream, but during expansion we may be removing attributes as we go
57 // If we've got inner attributes then the `tokens` we've got above holds
58 // these inner attributes. If an inner attribute is expanded we won't
59 // actually remove it from the token stream, so we'll just keep yielding
60 // it (bad!). To work around this case for now we just avoid recording
61 // `tokens` if we detect any inner attributes. This should help keep
62 // expansion correct, but we should fix this bug one day!
65 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
66 i.tokens = Some(tokens);
73 /// Parses one of the items allowed by the flags.
74 fn parse_item_implementation(
76 attrs: Vec<Attribute>,
78 attributes_allowed: bool,
79 ) -> PResult<'a, Option<P<Item>>> {
80 maybe_whole!(self, NtItem, |item| {
81 let mut item = item.into_inner();
82 let mut attrs = attrs;
83 mem::swap(&mut item.attrs, &mut attrs);
84 item.attrs.extend(attrs);
88 let lo = self.token.span;
90 let vis = self.parse_visibility(FollowedByType::No)?;
92 if self.eat_keyword(kw::Use) {
94 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
97 let span = lo.to(self.prev_span);
98 let item = self.mk_item(span, Ident::invalid(), item_, vis, attrs);
99 return Ok(Some(item));
102 if self.eat_keyword(kw::Extern) {
103 let extern_sp = self.prev_span;
104 if self.eat_keyword(kw::Crate) {
105 return Ok(Some(self.parse_item_extern_crate(lo, vis, attrs)?));
108 let abi = self.parse_abi();
110 if self.eat_keyword(kw::Fn) {
111 // EXTERN FUNCTION ITEM
112 let fn_span = self.prev_span;
113 let header = FnHeader {
114 unsafety: Unsafety::Normal,
115 asyncness: respan(fn_span, IsAsync::NotAsync),
116 constness: respan(fn_span, Constness::NotConst),
117 ext: Extern::from_abi(abi),
119 return self.parse_item_fn(lo, vis, attrs, header);
120 } else if self.check(&token::OpenDelim(token::Brace)) {
122 self.parse_item_foreign_mod(lo, abi, vis, attrs, extern_sp)?,
129 if self.is_static_global() {
132 let m = self.parse_mutability();
133 let info = self.parse_item_const(Some(m))?;
134 return self.mk_item_with_info(attrs, lo, vis, info);
137 if self.eat_keyword(kw::Const) {
138 let const_span = self.prev_span;
139 if [kw::Fn, kw::Unsafe, kw::Extern].iter().any(|k| self.check_keyword(*k)) {
140 // CONST FUNCTION ITEM
141 let unsafety = self.parse_unsafety();
143 if self.check_keyword(kw::Extern) {
144 self.sess.gated_spans.gate(sym::const_extern_fn, lo.to(self.token.span));
146 let ext = self.parse_extern()?;
149 let header = FnHeader {
151 asyncness: respan(const_span, IsAsync::NotAsync),
152 constness: respan(const_span, Constness::Const),
155 return self.parse_item_fn(lo, vis, attrs, header);
159 if self.eat_keyword(kw::Mut) {
160 let prev_span = self.prev_span;
161 self.struct_span_err(prev_span, "const globals cannot be mutable")
162 .span_label(prev_span, "cannot be mutable")
165 "you might want to declare a static instead",
167 Applicability::MaybeIncorrect,
172 let info = self.parse_item_const(None)?;
173 return self.mk_item_with_info(attrs, lo, vis, info);
176 // Parses `async unsafe? fn`.
177 if self.check_keyword(kw::Async) {
178 let async_span = self.token.span;
179 if self.is_keyword_ahead(1, &[kw::Fn])
180 || self.is_keyword_ahead(2, &[kw::Fn])
182 // ASYNC FUNCTION ITEM
183 self.bump(); // `async`
184 let unsafety = self.parse_unsafety(); // `unsafe`?
185 self.expect_keyword(kw::Fn)?; // `fn`
186 let fn_span = self.prev_span;
187 let asyncness = respan(async_span, IsAsync::Async {
188 closure_id: DUMMY_NODE_ID,
189 return_impl_trait_id: DUMMY_NODE_ID,
191 self.ban_async_in_2015(async_span);
192 let header = FnHeader {
195 constness: respan(fn_span, Constness::NotConst),
198 return self.parse_item_fn(lo, vis, attrs, header);
202 if self.check_keyword(kw::Unsafe) &&
203 self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
206 self.bump(); // `unsafe`
207 let info = self.parse_item_trait(lo, Unsafety::Unsafe)?;
208 return self.mk_item_with_info(attrs, lo, vis, info);
211 if self.check_keyword(kw::Impl) ||
212 self.check_keyword(kw::Unsafe) &&
213 self.is_keyword_ahead(1, &[kw::Impl]) ||
214 self.check_keyword(kw::Default) &&
215 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe])
218 let defaultness = self.parse_defaultness();
219 let unsafety = self.parse_unsafety();
220 self.expect_keyword(kw::Impl)?;
221 let info = self.parse_item_impl(unsafety, defaultness)?;
222 return self.mk_item_with_info(attrs, lo, vis, info);
225 if self.check_keyword(kw::Fn) {
228 let fn_span = self.prev_span;
229 let header = FnHeader {
230 unsafety: Unsafety::Normal,
231 asyncness: respan(fn_span, IsAsync::NotAsync),
232 constness: respan(fn_span, Constness::NotConst),
235 return self.parse_item_fn(lo, vis, attrs, header);
238 if self.check_keyword(kw::Unsafe)
239 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace))
241 // UNSAFE FUNCTION ITEM
242 self.bump(); // `unsafe`
243 // `{` is also expected after `unsafe`; in case of error, include it in the diagnostic.
244 self.check(&token::OpenDelim(token::Brace));
245 let ext = self.parse_extern()?;
246 self.expect_keyword(kw::Fn)?;
247 let fn_span = self.prev_span;
248 let header = FnHeader {
249 unsafety: Unsafety::Unsafe,
250 asyncness: respan(fn_span, IsAsync::NotAsync),
251 constness: respan(fn_span, Constness::NotConst),
254 return self.parse_item_fn(lo, vis, attrs, header);
257 if self.eat_keyword(kw::Mod) {
259 let info = self.parse_item_mod(&attrs[..])?;
260 return self.mk_item_with_info(attrs, lo, vis, info);
263 if self.eat_keyword(kw::Type) {
265 let (ident, ty, generics) = self.parse_type_alias()?;
266 let kind = ItemKind::TyAlias(ty, generics);
267 return self.mk_item_with_info(attrs, lo, vis, (ident, kind, None));
270 if self.eat_keyword(kw::Enum) {
272 let info = self.parse_item_enum()?;
273 return self.mk_item_with_info(attrs, lo, vis, info);
276 if self.check_keyword(kw::Trait)
277 || (self.check_keyword(kw::Auto)
278 && self.is_keyword_ahead(1, &[kw::Trait]))
281 let info = self.parse_item_trait(lo, Unsafety::Normal)?;
282 return self.mk_item_with_info(attrs, lo, vis, info);
285 if self.eat_keyword(kw::Struct) {
287 let info = self.parse_item_struct()?;
288 return self.mk_item_with_info(attrs, lo, vis, info);
291 if self.is_union_item() {
294 let info = self.parse_item_union()?;
295 return self.mk_item_with_info(attrs, lo, vis, info);
298 if let Some(macro_def) = self.eat_macro_def(&attrs, &vis, lo)? {
299 return Ok(Some(macro_def));
302 // Verify whether we have encountered a struct or method definition where the user forgot to
303 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
304 if vis.node.is_pub() &&
305 self.check_ident() &&
306 self.look_ahead(1, |t| *t != token::Not)
308 // Space between `pub` keyword and the identifier
311 // ^^^ `sp` points here
312 let sp = self.prev_span.between(self.token.span);
313 let full_sp = self.prev_span.to(self.token.span);
314 let ident_sp = self.token.span;
315 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
316 // possible public struct definition where `struct` was forgotten
317 let ident = self.parse_ident().unwrap();
318 let msg = format!("add `struct` here to parse `{}` as a public struct",
320 let mut err = self.diagnostic()
321 .struct_span_err(sp, "missing `struct` for struct definition");
322 err.span_suggestion_short(
323 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
326 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
327 let ident = self.parse_ident().unwrap();
329 let kw_name = self.recover_first_param();
330 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
331 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
332 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
334 ("fn", kw_name, false)
335 } else if self.check(&token::OpenDelim(token::Brace)) {
337 ("fn", kw_name, false)
338 } else if self.check(&token::Colon) {
342 ("fn` or `struct", "function or struct", true)
345 let msg = format!("missing `{}` for {} definition", kw, kw_name);
346 let mut err = self.diagnostic().struct_span_err(sp, &msg);
348 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
349 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
353 err.span_suggestion_short(
354 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
357 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
360 "if you meant to call a macro, try",
361 format!("{}!", snippet),
362 // this is the `ambiguous` conditional branch
363 Applicability::MaybeIncorrect
366 err.help("if you meant to call a macro, remove the `pub` \
367 and add a trailing `!` after the identifier");
371 } else if self.look_ahead(1, |t| *t == token::Lt) {
372 let ident = self.parse_ident().unwrap();
373 self.eat_to_tokens(&[&token::Gt]);
375 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
376 ("fn", self.recover_first_param(), false)
377 } else if self.check(&token::OpenDelim(token::Brace)) {
378 ("struct", "struct", false)
380 ("fn` or `struct", "function or struct", true)
382 let msg = format!("missing `{}` for {} definition", kw, kw_name);
383 let mut err = self.diagnostic().struct_span_err(sp, &msg);
385 err.span_suggestion_short(
387 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
389 Applicability::MachineApplicable,
395 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, vis)
398 pub(super) fn mk_item_with_info(
400 attrs: Vec<Attribute>,
404 ) -> PResult<'a, Option<P<Item>>> {
405 let (ident, item, extra_attrs) = info;
406 let span = lo.to(self.prev_span);
407 let attrs = Self::maybe_append(attrs, extra_attrs);
408 Ok(Some(self.mk_item(span, ident, item, vis, attrs)))
411 fn maybe_append<T>(mut lhs: Vec<T>, mut rhs: Option<Vec<T>>) -> Vec<T> {
412 if let Some(ref mut rhs) = rhs {
418 /// This is the fall-through for parsing items.
419 fn parse_macro_use_or_failure(
421 attrs: Vec<Attribute> ,
422 macros_allowed: bool,
423 attributes_allowed: bool,
425 visibility: Visibility
426 ) -> PResult<'a, Option<P<Item>>> {
427 if macros_allowed && self.token.is_path_start() &&
428 !(self.is_async_fn() && self.token.span.rust_2015()) {
429 // MACRO INVOCATION ITEM
431 let prev_span = self.prev_span;
432 self.complain_if_pub_macro(&visibility.node, prev_span);
435 let path = self.parse_path(PathStyle::Mod)?;
436 self.expect(&token::Not)?;
437 let args = self.parse_mac_args()?;
438 if args.need_semicolon() && !self.eat(&token::Semi) {
439 self.report_invalid_macro_expansion_item();
442 let hi = self.prev_span;
446 prior_type_ascription: self.last_type_ascription,
449 self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs);
450 return Ok(Some(item));
453 // FAILURE TO PARSE ITEM
454 match visibility.node {
455 VisibilityKind::Inherited => {}
457 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
461 if !attributes_allowed && !attrs.is_empty() {
462 self.expected_item_err(&attrs)?;
467 /// Emits an expected-item-after-attributes error.
468 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
469 let message = match attrs.last() {
470 Some(&Attribute { kind: AttrKind::DocComment(_), .. }) =>
471 "expected item after doc comment",
473 "expected item after attributes",
476 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
477 if attrs.last().unwrap().is_doc_comment() {
478 err.span_label(self.prev_span, "this doc comment doesn't document anything");
483 pub(super) fn is_async_fn(&self) -> bool {
484 self.token.is_keyword(kw::Async) &&
485 self.is_keyword_ahead(1, &[kw::Fn])
488 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
489 fn parse_assoc_macro_invoc(
492 vis: Option<&Visibility>,
494 ) -> PResult<'a, Option<Mac>> {
495 if self.token.is_path_start() &&
496 !(self.is_async_fn() && self.token.span.rust_2015()) {
497 let prev_span = self.prev_span;
498 let path = self.parse_path(PathStyle::Mod)?;
500 if path.segments.len() == 1 {
501 if !self.eat(&token::Not) {
502 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
505 self.expect(&token::Not)?;
508 if let Some(vis) = vis {
509 self.complain_if_pub_macro(&vis.node, prev_span);
514 // eat a matched-delimiter token tree:
515 let args = self.parse_mac_args()?;
516 if args.need_semicolon() {
523 prior_type_ascription: self.last_type_ascription,
530 fn missing_assoc_item_kind_err(
534 ) -> DiagnosticBuilder<'a> {
535 let expected_kinds = if item_type == "extern" {
536 "missing `fn`, `type`, or `static`"
538 "missing `fn`, `type`, or `const`"
541 // Given this code `path(`, it seems like this is not
542 // setting the visibility of a macro invocation, but rather
543 // a mistyped method declaration.
544 // Create a diagnostic pointing out that `fn` is missing.
546 // x | pub path(&self) {
547 // | ^ missing `fn`, `type`, or `const`
549 // ^^ `sp` below will point to this
550 let sp = prev_span.between(self.prev_span);
551 let mut err = self.diagnostic().struct_span_err(
553 &format!("{} for {}-item declaration",
554 expected_kinds, item_type));
555 err.span_label(sp, expected_kinds);
559 /// Parses an implementation item, `impl` keyword is already parsed.
561 /// impl<'a, T> TYPE { /* impl items */ }
562 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
563 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
565 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
566 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
567 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
568 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
569 -> PResult<'a, ItemInfo> {
570 // First, parse generic parameters if necessary.
571 let mut generics = if self.choose_generics_over_qpath() {
572 self.parse_generics()?
577 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
578 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
580 ast::ImplPolarity::Negative
582 ast::ImplPolarity::Positive
585 // Parse both types and traits as a type, then reinterpret if necessary.
586 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
587 let ty_first = if self.token.is_keyword(kw::For) &&
588 self.look_ahead(1, |t| t != &token::Lt) {
589 let span = self.prev_span.between(self.token.span);
590 self.struct_span_err(span, "missing trait in a trait impl").emit();
591 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
596 // If `for` is missing we try to recover.
597 let has_for = self.eat_keyword(kw::For);
598 let missing_for_span = self.prev_span.between(self.token.span);
600 let ty_second = if self.token == token::DotDot {
601 // We need to report this error after `cfg` expansion for compatibility reasons
602 self.bump(); // `..`, do not add it to expected tokens
603 Some(self.mk_ty(self.prev_span, TyKind::Err))
604 } else if has_for || self.token.can_begin_type() {
605 Some(self.parse_ty()?)
610 generics.where_clause = self.parse_where_clause()?;
612 let (impl_items, attrs) = self.parse_impl_body()?;
614 let item_kind = match ty_second {
616 // impl Trait for Type
618 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
619 .span_suggestion_short(
623 Applicability::MachineApplicable,
627 let ty_first = ty_first.into_inner();
628 let path = match ty_first.kind {
629 // This notably includes paths passed through `ty` macro fragments (#46438).
630 TyKind::Path(None, path) => path,
632 self.span_err(ty_first.span, "expected a trait, found type");
633 err_path(ty_first.span)
636 let trait_ref = TraitRef { path, ref_id: ty_first.id };
638 ItemKind::Impl(unsafety, polarity, defaultness,
639 generics, Some(trait_ref), ty_second, impl_items)
643 ItemKind::Impl(unsafety, polarity, defaultness,
644 generics, None, ty_first, impl_items)
648 Ok((Ident::invalid(), item_kind, Some(attrs)))
651 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
652 self.expect(&token::OpenDelim(token::Brace))?;
653 let attrs = self.parse_inner_attributes()?;
655 let mut impl_items = Vec::new();
656 while !self.eat(&token::CloseDelim(token::Brace)) {
657 let mut at_end = false;
658 match self.parse_impl_item(&mut at_end) {
659 Ok(impl_item) => impl_items.push(impl_item),
663 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
669 Ok((impl_items, attrs))
672 /// Parses an impl item.
673 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
674 maybe_whole!(self, NtImplItem, |x| x);
675 let attrs = self.parse_outer_attributes()?;
676 let mut unclosed_delims = vec![];
677 let (mut item, tokens) = self.collect_tokens(|this| {
678 let item = this.parse_impl_item_(at_end, attrs);
679 unclosed_delims.append(&mut this.unclosed_delims);
682 self.unclosed_delims.append(&mut unclosed_delims);
684 // See `parse_item` for why this clause is here.
685 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
686 item.tokens = Some(tokens);
694 mut attrs: Vec<Attribute>,
695 ) -> PResult<'a, ImplItem> {
696 let lo = self.token.span;
697 let vis = self.parse_visibility(FollowedByType::No)?;
698 let defaultness = self.parse_defaultness();
699 let (name, kind, generics) = if self.eat_keyword(kw::Type) {
700 let (name, ty, generics) = self.parse_type_alias()?;
701 (name, ast::ImplItemKind::TyAlias(ty), generics)
702 } else if self.is_const_item() {
703 self.parse_impl_const()?
704 } else if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(&vis), at_end)? {
705 // FIXME: code copied from `parse_macro_use_or_failure` -- use abstraction!
706 (Ident::invalid(), ast::ImplItemKind::Macro(mac), Generics::default())
708 let (name, inner_attrs, generics, kind) = self.parse_impl_method(at_end)?;
709 attrs.extend(inner_attrs);
710 (name, kind, generics)
715 span: lo.to(self.prev_span),
726 /// Parses defaultness (i.e., `default` or nothing).
727 fn parse_defaultness(&mut self) -> Defaultness {
728 // `pub` is included for better error messages
729 if self.check_keyword(kw::Default) &&
730 self.is_keyword_ahead(1, &[
741 self.bump(); // `default`
748 /// Returns `true` if we are looking at `const ID`
749 /// (returns `false` for things like `const fn`, etc.).
750 fn is_const_item(&self) -> bool {
751 self.token.is_keyword(kw::Const) &&
752 !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
755 /// This parses the grammar:
756 /// ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
757 fn parse_impl_const(&mut self) -> PResult<'a, (Ident, ImplItemKind, Generics)> {
758 self.expect_keyword(kw::Const)?;
759 let name = self.parse_ident()?;
760 self.expect(&token::Colon)?;
761 let typ = self.parse_ty()?;
762 self.expect(&token::Eq)?;
763 let expr = self.parse_expr()?;
765 Ok((name, ImplItemKind::Const(typ, expr), Generics::default()))
768 /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`.
769 fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
770 // Parse optional `auto` prefix.
771 let is_auto = if self.eat_keyword(kw::Auto) {
777 self.expect_keyword(kw::Trait)?;
778 let ident = self.parse_ident()?;
779 let mut tps = self.parse_generics()?;
781 // Parse optional colon and supertrait bounds.
782 let had_colon = self.eat(&token::Colon);
783 let span_at_colon = self.prev_span;
784 let bounds = if had_colon {
785 self.parse_generic_bounds(Some(self.prev_span))?
790 let span_before_eq = self.prev_span;
791 if self.eat(&token::Eq) {
792 // It's a trait alias.
794 let span = span_at_colon.to(span_before_eq);
795 self.struct_span_err(span, "bounds are not allowed on trait aliases")
799 let bounds = self.parse_generic_bounds(None)?;
800 tps.where_clause = self.parse_where_clause()?;
803 let whole_span = lo.to(self.prev_span);
804 if is_auto == IsAuto::Yes {
805 let msg = "trait aliases cannot be `auto`";
806 self.struct_span_err(whole_span, msg)
807 .span_label(whole_span, msg)
810 if unsafety != Unsafety::Normal {
811 let msg = "trait aliases cannot be `unsafe`";
812 self.struct_span_err(whole_span, msg)
813 .span_label(whole_span, msg)
817 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
819 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
821 // It's a normal trait.
822 tps.where_clause = self.parse_where_clause()?;
823 self.expect(&token::OpenDelim(token::Brace))?;
824 let mut trait_items = vec![];
825 while !self.eat(&token::CloseDelim(token::Brace)) {
826 if let token::DocComment(_) = self.token.kind {
827 if self.look_ahead(1,
828 |tok| tok == &token::CloseDelim(token::Brace)) {
833 "found a documentation comment that doesn't document anything",
836 "doc comments must come before what they document, maybe a \
837 comment was intended with `//`?",
844 let mut at_end = false;
845 match self.parse_trait_item(&mut at_end) {
846 Ok(item) => trait_items.push(item),
850 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
856 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
860 /// Parses the items in a trait declaration.
861 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
862 maybe_whole!(self, NtTraitItem, |x| x);
863 let attrs = self.parse_outer_attributes()?;
864 let mut unclosed_delims = vec![];
865 let (mut item, tokens) = self.collect_tokens(|this| {
866 let item = this.parse_trait_item_(at_end, attrs);
867 unclosed_delims.append(&mut this.unclosed_delims);
870 self.unclosed_delims.append(&mut unclosed_delims);
871 // See `parse_item` for why this clause is here.
872 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
873 item.tokens = Some(tokens);
878 fn parse_trait_item_(
881 mut attrs: Vec<Attribute>,
882 ) -> PResult<'a, TraitItem> {
883 let lo = self.token.span;
884 let vis = self.parse_visibility(FollowedByType::No)?;
885 let (name, kind, generics) = if self.eat_keyword(kw::Type) {
886 self.parse_trait_item_assoc_ty()?
887 } else if self.is_const_item() {
888 self.parse_trait_item_const()?
889 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
891 (Ident::invalid(), TraitItemKind::Macro(mac), Generics::default())
893 self.parse_trait_item_method(at_end, &mut attrs)?
903 span: lo.to(self.prev_span),
908 fn parse_trait_item_const(&mut self) -> PResult<'a, (Ident, TraitItemKind, Generics)> {
909 self.expect_keyword(kw::Const)?;
910 let ident = self.parse_ident()?;
911 self.expect(&token::Colon)?;
912 let ty = self.parse_ty()?;
913 let default = if self.eat(&token::Eq) {
914 Some(self.parse_expr()?)
919 Ok((ident, TraitItemKind::Const(ty, default), Generics::default()))
922 /// Parses the following grammar:
924 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
925 fn parse_trait_item_assoc_ty(&mut self) -> PResult<'a, (Ident, TraitItemKind, Generics)> {
926 let ident = self.parse_ident()?;
927 let mut generics = self.parse_generics()?;
929 // Parse optional colon and param bounds.
930 let bounds = if self.eat(&token::Colon) {
931 self.parse_generic_bounds(None)?
935 generics.where_clause = self.parse_where_clause()?;
937 let default = if self.eat(&token::Eq) {
938 Some(self.parse_ty()?)
944 Ok((ident, TraitItemKind::Type(bounds, default), generics))
947 /// Parses a `UseTree`.
950 /// USE_TREE = [`::`] `*` |
951 /// [`::`] `{` USE_TREE_LIST `}` |
953 /// PATH `::` `{` USE_TREE_LIST `}` |
954 /// PATH [`as` IDENT]
956 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
957 let lo = self.token.span;
959 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
960 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
961 self.check(&token::BinOp(token::Star)) ||
962 self.is_import_coupler() {
963 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
964 let mod_sep_ctxt = self.token.span.ctxt();
965 if self.eat(&token::ModSep) {
966 prefix.segments.push(
967 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
971 self.parse_use_tree_glob_or_nested()?
973 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
974 prefix = self.parse_path(PathStyle::Mod)?;
976 if self.eat(&token::ModSep) {
977 self.parse_use_tree_glob_or_nested()?
979 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
983 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
986 /// Parses `*` or `{...}`.
987 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
988 Ok(if self.eat(&token::BinOp(token::Star)) {
991 UseTreeKind::Nested(self.parse_use_tree_list()?)
995 /// Parses a `UseTreeKind::Nested(list)`.
998 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
1000 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
1001 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
1005 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
1006 if self.eat_keyword(kw::As) {
1007 self.parse_ident_or_underscore().map(Some)
1013 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1014 match self.token.kind {
1015 token::Ident(name, false) if name == kw::Underscore => {
1016 let span = self.token.span;
1018 Ok(Ident::new(name, span))
1020 _ => self.parse_ident(),
1024 /// Parses `extern crate` links.
1029 /// extern crate foo;
1030 /// extern crate bar as foo;
1032 fn parse_item_extern_crate(
1035 visibility: Visibility,
1036 attrs: Vec<Attribute>
1037 ) -> PResult<'a, P<Item>> {
1038 // Accept `extern crate name-like-this` for better diagnostics
1039 let orig_name = self.parse_crate_name_with_dashes()?;
1040 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1041 (rename, Some(orig_name.name))
1045 self.expect_semi()?;
1047 let span = lo.to(self.prev_span);
1048 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
1051 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
1052 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1053 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1055 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1056 self.parse_path_segment_ident()
1060 let mut idents = vec![];
1061 let mut replacement = vec![];
1062 let mut fixed_crate_name = false;
1063 // Accept `extern crate name-like-this` for better diagnostics.
1064 let dash = token::BinOp(token::BinOpToken::Minus);
1065 if self.token == dash { // Do not include `-` as part of the expected tokens list.
1066 while self.eat(&dash) {
1067 fixed_crate_name = true;
1068 replacement.push((self.prev_span, "_".to_string()));
1069 idents.push(self.parse_ident()?);
1072 if fixed_crate_name {
1073 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1074 let mut fixed_name = format!("{}", ident.name);
1075 for part in idents {
1076 fixed_name.push_str(&format!("_{}", part.name));
1078 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1080 self.struct_span_err(fixed_name_sp, error_msg)
1081 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1082 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1088 /// Parses `extern` for foreign ABIs modules.
1090 /// `extern` is expected to have been
1091 /// consumed before calling this method.
1095 /// ```ignore (only-for-syntax-highlight)
1099 fn parse_item_foreign_mod(
1102 abi: Option<StrLit>,
1103 visibility: Visibility,
1104 mut attrs: Vec<Attribute>,
1106 ) -> PResult<'a, P<Item>> {
1107 self.expect(&token::OpenDelim(token::Brace))?;
1109 attrs.extend(self.parse_inner_attributes()?);
1111 let mut foreign_items = vec![];
1112 while !self.eat(&token::CloseDelim(token::Brace)) {
1113 foreign_items.push(self.parse_foreign_item(extern_sp)?);
1116 let prev_span = self.prev_span;
1117 let m = ast::ForeignMod {
1119 items: foreign_items
1121 let invalid = Ident::invalid();
1122 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
1125 /// Parses a foreign item.
1126 pub fn parse_foreign_item(&mut self, extern_sp: Span) -> PResult<'a, ForeignItem> {
1127 maybe_whole!(self, NtForeignItem, |ni| ni);
1129 let attrs = self.parse_outer_attributes()?;
1130 let lo = self.token.span;
1131 let visibility = self.parse_visibility(FollowedByType::No)?;
1133 // FOREIGN STATIC ITEM
1134 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
1135 if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
1136 if self.token.is_keyword(kw::Const) {
1138 .struct_span_err(self.token.span, "extern items cannot be `const`");
1141 // The user wrote 'const fn'
1142 if self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) {
1146 // Consume `unsafe` if present, since `extern` blocks
1147 // don't allow it. This will leave behind a plain 'fn'
1148 self.eat_keyword(kw::Unsafe);
1149 // Treat 'const fn` as a plain `fn` for error recovery purposes.
1150 // We've already emitted an error, so compilation is guaranteed
1152 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
1154 err.span_suggestion(
1156 "try using a static value",
1157 "static".to_owned(),
1158 Applicability::MachineApplicable
1162 self.bump(); // `static` or `const`
1163 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
1165 // FOREIGN FUNCTION ITEM
1166 if self.check_keyword(kw::Fn) {
1167 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?);
1169 // FOREIGN TYPE ITEM
1170 if self.check_keyword(kw::Type) {
1171 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
1174 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
1178 ident: Ident::invalid(),
1179 span: lo.to(self.prev_span),
1183 kind: ForeignItemKind::Macro(mac),
1188 if !attrs.is_empty() {
1189 self.expected_item_err(&attrs)?;
1197 /// Parses a static item from a foreign module.
1198 /// Assumes that the `static` keyword is already parsed.
1199 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
1200 -> PResult<'a, ForeignItem> {
1201 let mutbl = self.parse_mutability();
1202 let ident = self.parse_ident()?;
1203 self.expect(&token::Colon)?;
1204 let ty = self.parse_ty()?;
1205 let hi = self.token.span;
1206 self.expect_semi()?;
1210 kind: ForeignItemKind::Static(ty, mutbl),
1217 /// Parses a type from a foreign module.
1218 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
1219 -> PResult<'a, ForeignItem> {
1220 self.expect_keyword(kw::Type)?;
1222 let ident = self.parse_ident()?;
1223 let hi = self.token.span;
1224 self.expect_semi()?;
1225 Ok(ast::ForeignItem {
1228 kind: ForeignItemKind::Ty,
1235 fn is_static_global(&mut self) -> bool {
1236 if self.check_keyword(kw::Static) {
1237 // Check if this could be a closure.
1238 !self.look_ahead(1, |token| {
1239 if token.is_keyword(kw::Move) {
1243 token::BinOp(token::Or) | token::OrOr => true,
1252 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty = $expr` with
1253 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1255 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1256 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
1257 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1259 // Parse the type of a `const` or `static mut?` item.
1260 // That is, the `":" $ty` fragment.
1261 let ty = if self.token == token::Eq {
1262 self.recover_missing_const_type(id, m)
1264 // Not `=` so expect `":"" $ty` as usual.
1265 self.expect(&token::Colon)?;
1269 self.expect(&token::Eq)?;
1270 let e = self.parse_expr()?;
1271 self.expect_semi()?;
1272 let item = match m {
1273 Some(m) => ItemKind::Static(ty, m, e),
1274 None => ItemKind::Const(ty, e),
1276 Ok((id, item, None))
1279 /// We were supposed to parse `:` but instead, we're already at `=`.
1280 /// This means that the type is missing.
1281 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1282 // Construct the error and stash it away with the hope
1283 // that typeck will later enrich the error with a type.
1284 let kind = match m {
1285 Some(Mutability::Mutable) => "static mut",
1286 Some(Mutability::Immutable) => "static",
1289 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1290 err.span_suggestion(
1292 "provide a type for the item",
1293 format!("{}: <type>", id),
1294 Applicability::HasPlaceholders,
1296 err.stash(id.span, StashKey::ItemNoType);
1298 // The user intended that the type be inferred,
1299 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1301 kind: TyKind::Infer,
1303 id: ast::DUMMY_NODE_ID,
1307 /// Parses the grammar:
1308 /// Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
1309 fn parse_type_alias(&mut self) -> PResult<'a, (Ident, P<Ty>, Generics)> {
1310 let ident = self.parse_ident()?;
1311 let mut tps = self.parse_generics()?;
1312 tps.where_clause = self.parse_where_clause()?;
1313 self.expect(&token::Eq)?;
1314 let ty = self.parse_ty()?;
1315 self.expect_semi()?;
1316 Ok((ident, ty, tps))
1319 /// Parses an enum declaration.
1320 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1321 let id = self.parse_ident()?;
1322 let mut generics = self.parse_generics()?;
1323 generics.where_clause = self.parse_where_clause()?;
1325 let (variants, _) = self.parse_delim_comma_seq(
1327 |p| p.parse_enum_variant(),
1329 self.recover_stmt();
1333 let enum_definition = EnumDef {
1334 variants: variants.into_iter().filter_map(|v| v).collect(),
1336 Ok((id, ItemKind::Enum(enum_definition, generics), None))
1339 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1340 let variant_attrs = self.parse_outer_attributes()?;
1341 let vlo = self.token.span;
1343 let vis = self.parse_visibility(FollowedByType::No)?;
1344 if !self.recover_nested_adt_item(kw::Enum)? {
1347 let ident = self.parse_ident()?;
1349 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1350 // Parse a struct variant.
1351 let (fields, recovered) = self.parse_record_struct_body()?;
1352 VariantData::Struct(fields, recovered)
1353 } else if self.check(&token::OpenDelim(token::Paren)) {
1355 self.parse_tuple_struct_body()?,
1359 VariantData::Unit(DUMMY_NODE_ID)
1362 let disr_expr = if self.eat(&token::Eq) {
1365 value: self.parse_expr()?,
1371 let vr = ast::Variant {
1375 attrs: variant_attrs,
1378 span: vlo.to(self.prev_span),
1379 is_placeholder: false,
1385 /// Parses `struct Foo { ... }`.
1386 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1387 let class_name = self.parse_ident()?;
1389 let mut generics = self.parse_generics()?;
1391 // There is a special case worth noting here, as reported in issue #17904.
1392 // If we are parsing a tuple struct it is the case that the where clause
1393 // should follow the field list. Like so:
1395 // struct Foo<T>(T) where T: Copy;
1397 // If we are parsing a normal record-style struct it is the case
1398 // that the where clause comes before the body, and after the generics.
1399 // So if we look ahead and see a brace or a where-clause we begin
1400 // parsing a record style struct.
1402 // Otherwise if we look ahead and see a paren we parse a tuple-style
1405 let vdata = if self.token.is_keyword(kw::Where) {
1406 generics.where_clause = self.parse_where_clause()?;
1407 if self.eat(&token::Semi) {
1408 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1409 VariantData::Unit(DUMMY_NODE_ID)
1411 // If we see: `struct Foo<T> where T: Copy { ... }`
1412 let (fields, recovered) = self.parse_record_struct_body()?;
1413 VariantData::Struct(fields, recovered)
1415 // No `where` so: `struct Foo<T>;`
1416 } else if self.eat(&token::Semi) {
1417 VariantData::Unit(DUMMY_NODE_ID)
1418 // Record-style struct definition
1419 } else if self.token == token::OpenDelim(token::Brace) {
1420 let (fields, recovered) = self.parse_record_struct_body()?;
1421 VariantData::Struct(fields, recovered)
1422 // Tuple-style struct definition with optional where-clause.
1423 } else if self.token == token::OpenDelim(token::Paren) {
1424 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1425 generics.where_clause = self.parse_where_clause()?;
1426 self.expect_semi()?;
1429 let token_str = self.this_token_descr();
1430 let mut err = self.fatal(&format!(
1431 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1434 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1438 Ok((class_name, ItemKind::Struct(vdata, generics), None))
1441 /// Parses `union Foo { ... }`.
1442 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1443 let class_name = self.parse_ident()?;
1445 let mut generics = self.parse_generics()?;
1447 let vdata = if self.token.is_keyword(kw::Where) {
1448 generics.where_clause = self.parse_where_clause()?;
1449 let (fields, recovered) = self.parse_record_struct_body()?;
1450 VariantData::Struct(fields, recovered)
1451 } else if self.token == token::OpenDelim(token::Brace) {
1452 let (fields, recovered) = self.parse_record_struct_body()?;
1453 VariantData::Struct(fields, recovered)
1455 let token_str = self.this_token_descr();
1456 let mut err = self.fatal(&format!(
1457 "expected `where` or `{{` after union name, found {}", token_str));
1458 err.span_label(self.token.span, "expected `where` or `{` after union name");
1462 Ok((class_name, ItemKind::Union(vdata, generics), None))
1465 pub(super) fn is_union_item(&self) -> bool {
1466 self.token.is_keyword(kw::Union) &&
1467 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
1470 fn parse_record_struct_body(
1472 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1473 let mut fields = Vec::new();
1474 let mut recovered = false;
1475 if self.eat(&token::OpenDelim(token::Brace)) {
1476 while self.token != token::CloseDelim(token::Brace) {
1477 let field = self.parse_struct_decl_field().map_err(|e| {
1478 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1483 Ok(field) => fields.push(field),
1490 self.eat(&token::CloseDelim(token::Brace));
1492 let token_str = self.this_token_descr();
1493 let mut err = self.fatal(&format!(
1494 "expected `where`, or `{{` after struct name, found {}", token_str));
1495 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1499 Ok((fields, recovered))
1502 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1503 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1504 // Unit like structs are handled in parse_item_struct function
1505 self.parse_paren_comma_seq(|p| {
1506 let attrs = p.parse_outer_attributes()?;
1507 let lo = p.token.span;
1508 let vis = p.parse_visibility(FollowedByType::Yes)?;
1509 let ty = p.parse_ty()?;
1511 span: lo.to(ty.span),
1517 is_placeholder: false,
1522 /// Parses an element of a struct declaration.
1523 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1524 let attrs = self.parse_outer_attributes()?;
1525 let lo = self.token.span;
1526 let vis = self.parse_visibility(FollowedByType::No)?;
1527 self.parse_single_struct_field(lo, vis, attrs)
1530 /// Parses a structure field declaration.
1531 fn parse_single_struct_field(&mut self,
1534 attrs: Vec<Attribute> )
1535 -> PResult<'a, StructField> {
1536 let mut seen_comma: bool = false;
1537 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1538 if self.token == token::Comma {
1541 match self.token.kind {
1545 token::CloseDelim(token::Brace) => {}
1546 token::DocComment(_) => {
1547 let previous_span = self.prev_span;
1548 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1549 self.bump(); // consume the doc comment
1550 let comma_after_doc_seen = self.eat(&token::Comma);
1551 // `seen_comma` is always false, because we are inside doc block
1552 // condition is here to make code more readable
1553 if seen_comma == false && comma_after_doc_seen == true {
1556 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1559 if seen_comma == false {
1560 let sp = self.sess.source_map().next_point(previous_span);
1561 err.span_suggestion(
1563 "missing comma here",
1565 Applicability::MachineApplicable
1572 let sp = self.sess.source_map().next_point(self.prev_span);
1573 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
1574 self.this_token_descr()));
1575 if self.token.is_ident() {
1576 // This is likely another field; emit the diagnostic and keep going
1577 err.span_suggestion(
1579 "try adding a comma",
1581 Applicability::MachineApplicable,
1592 /// Parses a structure field.
1593 fn parse_name_and_ty(
1597 attrs: Vec<Attribute>
1598 ) -> PResult<'a, StructField> {
1599 let name = self.parse_ident()?;
1600 self.expect(&token::Colon)?;
1601 let ty = self.parse_ty()?;
1603 span: lo.to(self.prev_span),
1609 is_placeholder: false,
1613 pub(super) fn eat_macro_def(
1615 attrs: &[Attribute],
1618 ) -> PResult<'a, Option<P<Item>>> {
1619 let (ident, def) = if self.eat_keyword(kw::Macro) {
1620 let ident = self.parse_ident()?;
1621 let body = if self.check(&token::OpenDelim(token::Brace)) {
1622 self.parse_mac_args()?
1623 } else if self.check(&token::OpenDelim(token::Paren)) {
1624 let params = self.parse_token_tree();
1625 let pspan = params.span();
1626 let body = if self.check(&token::OpenDelim(token::Brace)) {
1627 self.parse_token_tree()
1629 return self.unexpected();
1631 let bspan = body.span();
1632 let tokens = TokenStream::new(vec![
1634 TokenTree::token(token::FatArrow, pspan.between(bspan)).into(),
1637 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1638 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1640 return self.unexpected();
1643 (ident, ast::MacroDef { body, legacy: false })
1644 } else if self.check_keyword(sym::macro_rules) &&
1645 self.look_ahead(1, |t| *t == token::Not) &&
1646 self.look_ahead(2, |t| t.is_ident()) {
1647 let prev_span = self.prev_span;
1648 self.complain_if_pub_macro(&vis.node, prev_span);
1652 let ident = self.parse_ident()?;
1653 let body = self.parse_mac_args()?;
1654 if body.need_semicolon() && !self.eat(&token::Semi) {
1655 self.report_invalid_macro_expansion_item();
1658 (ident, ast::MacroDef { body, legacy: true })
1663 let span = lo.to(self.prev_span);
1666 self.sess.gated_spans.gate(sym::decl_macro, span);
1669 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
1672 fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
1674 VisibilityKind::Inherited => {}
1676 let mut err = if self.token.is_keyword(sym::macro_rules) {
1677 let mut err = self.diagnostic()
1678 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
1679 err.span_suggestion(
1681 "try exporting the macro",
1682 "#[macro_export]".to_owned(),
1683 Applicability::MaybeIncorrect // speculative
1687 let mut err = self.diagnostic()
1688 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
1689 err.help("try adjusting the macro to put `pub` inside the invocation");
1697 fn report_invalid_macro_expansion_item(&self) {
1698 let has_close_delim = self.sess.source_map()
1699 .span_to_snippet(self.prev_span)
1700 .map(|s| s.ends_with(")") || s.ends_with("]"))
1702 let right_brace_span = if has_close_delim {
1703 // it's safe to peel off one character only when it has the close delim
1704 self.prev_span.with_lo(self.prev_span.hi() - BytePos(1))
1706 self.sess.source_map().next_point(self.prev_span)
1709 self.struct_span_err(
1711 "macros that expand to items must be delimited with braces or followed by a semicolon",
1712 ).multipart_suggestion(
1713 "change the delimiters to curly braces",
1715 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), "{".to_string()),
1716 (right_brace_span, '}'.to_string()),
1718 Applicability::MaybeIncorrect,
1720 self.sess.source_map().next_point(self.prev_span),
1723 Applicability::MaybeIncorrect,
1727 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1728 /// it is, we try to parse the item and report error about nested types.
1729 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1730 if (self.token.is_keyword(kw::Enum) ||
1731 self.token.is_keyword(kw::Struct) ||
1732 self.token.is_keyword(kw::Union))
1733 && self.look_ahead(1, |t| t.is_ident())
1735 let kw_token = self.token.clone();
1736 let kw_str = pprust::token_to_string(&kw_token);
1737 let item = self.parse_item()?;
1739 self.struct_span_err(
1741 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1744 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1746 Applicability::MaybeIncorrect,
1748 // We successfully parsed the item but we must inform the caller about nested problem.
1754 fn mk_item(&self, span: Span, ident: Ident, kind: ItemKind, vis: Visibility,
1755 attrs: Vec<Attribute>) -> P<Item> {
1768 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1769 pub(super) struct ParamCfg {
1770 /// Is `self` is allowed as the first parameter?
1771 pub is_self_allowed: bool,
1772 /// Is `...` allowed as the tail of the parameter list?
1773 pub allow_c_variadic: bool,
1774 /// `is_name_required` decides if, per-parameter,
1775 /// the parameter must have a pattern or just a type.
1776 pub is_name_required: fn(&token::Token) -> bool,
1779 /// Parsing of functions and methods.
1780 impl<'a> Parser<'a> {
1781 /// Parses an item-position function declaration.
1786 attrs: Vec<Attribute>,
1788 ) -> PResult<'a, Option<P<Item>>> {
1789 let is_c_abi = match header.ext {
1790 ast::Extern::None => false,
1791 ast::Extern::Implicit => true,
1792 ast::Extern::Explicit(abi) => abi.symbol_unescaped == sym::C,
1794 let (ident, decl, generics) = self.parse_fn_sig(ParamCfg {
1795 is_self_allowed: false,
1796 // FIXME: Parsing should not depend on ABI or unsafety and
1797 // the variadic parameter should always be parsed.
1798 allow_c_variadic: is_c_abi && header.unsafety == Unsafety::Unsafe,
1799 is_name_required: |_| true,
1801 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1802 let kind = ItemKind::Fn(FnSig { decl, header }, generics, body);
1803 self.mk_item_with_info(attrs, lo, vis, (ident, kind, Some(inner_attrs)))
1806 /// Parses a function declaration from a foreign module.
1807 fn parse_item_foreign_fn(
1809 vis: ast::Visibility,
1811 attrs: Vec<Attribute>,
1813 ) -> PResult<'a, ForeignItem> {
1814 self.expect_keyword(kw::Fn)?;
1815 let (ident, decl, generics) = self.parse_fn_sig(ParamCfg {
1816 is_self_allowed: false,
1817 allow_c_variadic: true,
1818 is_name_required: |_| true,
1820 let span = lo.to(self.token.span);
1821 self.parse_semi_or_incorrect_foreign_fn_body(&ident, extern_sp)?;
1822 Ok(ast::ForeignItem {
1825 kind: ForeignItemKind::Fn(decl, generics),
1832 /// Parses a method or a macro invocation in a trait impl.
1833 fn parse_impl_method(
1836 ) -> PResult<'a, (Ident, Vec<Attribute>, Generics, ImplItemKind)> {
1837 let (ident, sig, generics) = self.parse_method_sig(|_| true)?;
1839 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1840 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(sig, body)))
1843 fn parse_trait_item_method(
1846 attrs: &mut Vec<Attribute>,
1847 ) -> PResult<'a, (Ident, TraitItemKind, Generics)> {
1848 // This is somewhat dubious; We don't want to allow
1849 // argument names to be left off if there is a definition...
1851 // We don't allow argument names to be left off in edition 2018.
1852 let (ident, sig, generics) = self.parse_method_sig(|t| t.span.rust_2018())?;
1853 let body = self.parse_trait_method_body(at_end, attrs)?;
1854 Ok((ident, TraitItemKind::Method(sig, body), generics))
1857 /// Parse the "body" of a method in a trait item definition.
1858 /// This can either be `;` when there's no body,
1859 /// or e.g. a block when the method is a provided one.
1860 fn parse_trait_method_body(
1863 attrs: &mut Vec<Attribute>,
1864 ) -> PResult<'a, Option<P<Block>>> {
1865 Ok(match self.token.kind {
1867 debug!("parse_trait_method_body(): parsing required method");
1872 token::OpenDelim(token::Brace) => {
1873 debug!("parse_trait_method_body(): parsing provided method");
1875 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1876 attrs.extend(inner_attrs.iter().cloned());
1879 token::Interpolated(ref nt) => {
1881 token::NtBlock(..) => {
1883 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1884 attrs.extend(inner_attrs.iter().cloned());
1887 _ => return self.expected_semi_or_open_brace(),
1890 _ => return self.expected_semi_or_open_brace(),
1894 /// Parse the "signature", including the identifier, parameters, and generics
1895 /// of a method. The body is not parsed as that differs between `trait`s and `impl`s.
1896 fn parse_method_sig(
1898 is_name_required: fn(&token::Token) -> bool,
1899 ) -> PResult<'a, (Ident, FnSig, Generics)> {
1900 let header = self.parse_fn_front_matter()?;
1901 let (ident, decl, generics) = self.parse_fn_sig(ParamCfg {
1902 is_self_allowed: true,
1903 allow_c_variadic: false,
1906 Ok((ident, FnSig { header, decl }, generics))
1909 /// Parses all the "front matter" for a `fn` declaration, up to
1910 /// and including the `fn` keyword:
1914 /// - `const unsafe fn`
1917 fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1918 let is_const_fn = self.eat_keyword(kw::Const);
1919 let const_span = self.prev_span;
1920 let asyncness = self.parse_asyncness();
1921 if let IsAsync::Async { .. } = asyncness {
1922 self.ban_async_in_2015(self.prev_span);
1924 let asyncness = respan(self.prev_span, asyncness);
1925 let unsafety = self.parse_unsafety();
1926 let (constness, unsafety, ext) = if is_const_fn {
1927 (respan(const_span, Constness::Const), unsafety, Extern::None)
1929 let ext = self.parse_extern()?;
1930 (respan(self.prev_span, Constness::NotConst), unsafety, ext)
1932 if !self.eat_keyword(kw::Fn) {
1933 // It is possible for `expect_one_of` to recover given the contents of
1934 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1935 // account for this.
1936 if !self.expect_one_of(&[], &[])? { unreachable!() }
1938 Ok(FnHeader { constness, unsafety, asyncness, ext })
1941 /// Parse the "signature", including the identifier, parameters, and generics of a function.
1942 fn parse_fn_sig(&mut self, cfg: ParamCfg) -> PResult<'a, (Ident, P<FnDecl>, Generics)> {
1943 let ident = self.parse_ident()?;
1944 let mut generics = self.parse_generics()?;
1945 let decl = self.parse_fn_decl(cfg, true)?;
1946 generics.where_clause = self.parse_where_clause()?;
1947 Ok((ident, decl, generics))
1950 /// Parses the parameter list and result type of a function declaration.
1951 pub(super) fn parse_fn_decl(
1954 ret_allow_plus: bool,
1955 ) -> PResult<'a, P<FnDecl>> {
1957 inputs: self.parse_fn_params(cfg)?,
1958 output: self.parse_ret_ty(ret_allow_plus)?,
1962 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1963 fn parse_fn_params(&mut self, mut cfg: ParamCfg) -> PResult<'a, Vec<Param>> {
1964 let sp = self.token.span;
1965 let is_trait_item = cfg.is_self_allowed;
1966 let mut c_variadic = false;
1967 // Parse the arguments, starting out with `self` being possibly allowed...
1968 let (params, _) = self.parse_paren_comma_seq(|p| {
1969 let param = p.parse_param_general(&cfg, is_trait_item);
1970 // ...now that we've parsed the first argument, `self` is no longer allowed.
1971 cfg.is_self_allowed = false;
1975 if let TyKind::CVarArgs = param.ty.kind {
1977 if p.token != token::CloseDelim(token::Paren) {
1980 "`...` must be the last argument of a C-variadic function",
1982 // FIXME(eddyb) this should probably still push `CVarArgs`.
1983 // Maybe AST validation/HIR lowering should emit the above error?
1994 let lo = p.prev_span;
1995 // Skip every token until next possible arg or end.
1996 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1997 // Create a placeholder argument for proper arg count (issue #34264).
1998 let span = lo.to(p.prev_span);
1999 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
2004 let mut params: Vec<_> = params.into_iter().filter_map(|x| x).collect();
2006 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2007 self.deduplicate_recovered_params_names(&mut params);
2009 if c_variadic && params.len() <= 1 {
2012 "C-variadic function must be declared with at least one named argument",
2019 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
2021 /// This version of parse param doesn't necessarily require identifier names.
2022 fn parse_param_general(&mut self, cfg: &ParamCfg, is_trait_item: bool) -> PResult<'a, Param> {
2023 let lo = self.token.span;
2024 let attrs = self.parse_outer_attributes()?;
2026 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2027 if let Some(mut param) = self.parse_self_param()? {
2028 param.attrs = attrs.into();
2029 return if cfg.is_self_allowed {
2032 self.recover_bad_self_param(param, is_trait_item)
2036 let is_name_required = match self.token.kind {
2037 token::DotDotDot => false,
2038 _ => (cfg.is_name_required)(&self.token),
2040 let (pat, ty) = if is_name_required || self.is_named_param() {
2041 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2043 let pat = self.parse_fn_param_pat()?;
2044 if let Err(mut err) = self.expect(&token::Colon) {
2045 return if let Some(ident) = self.parameter_without_type(
2049 cfg.is_self_allowed,
2053 Ok(dummy_arg(ident))
2059 self.eat_incorrect_doc_comment_for_param_type();
2060 (pat, self.parse_ty_common(true, true, cfg.allow_c_variadic)?)
2062 debug!("parse_param_general ident_to_pat");
2063 let parser_snapshot_before_ty = self.clone();
2064 self.eat_incorrect_doc_comment_for_param_type();
2065 let mut ty = self.parse_ty_common(true, true, cfg.allow_c_variadic);
2066 if ty.is_ok() && self.token != token::Comma &&
2067 self.token != token::CloseDelim(token::Paren) {
2068 // This wasn't actually a type, but a pattern looking like a type,
2069 // so we are going to rollback and re-parse for recovery.
2070 ty = self.unexpected();
2074 let ident = Ident::new(kw::Invalid, self.prev_span);
2075 let bm = BindingMode::ByValue(Mutability::Immutable);
2076 let pat = self.mk_pat_ident(ty.span, bm, ident);
2079 // If this is a C-variadic argument and we hit an error, return the error.
2080 Err(err) if self.token == token::DotDotDot => return Err(err),
2081 // Recover from attempting to parse the argument as a type without pattern.
2084 mem::replace(self, parser_snapshot_before_ty);
2085 self.recover_arg_parse()?
2090 let span = lo.to(self.token.span);
2093 attrs: attrs.into(),
2094 id: ast::DUMMY_NODE_ID,
2095 is_placeholder: false,
2102 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2104 /// See `parse_self_param_with_attrs` to collect attributes.
2105 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2106 // Extract an identifier *after* having confirmed that the token is one.
2107 let expect_self_ident = |this: &mut Self| {
2108 match this.token.kind {
2109 // Preserve hygienic context.
2110 token::Ident(name, _) => {
2111 let span = this.token.span;
2113 Ident::new(name, span)
2115 _ => unreachable!(),
2118 // Is `self` `n` tokens ahead?
2119 let is_isolated_self = |this: &Self, n| {
2120 this.is_keyword_ahead(n, &[kw::SelfLower])
2121 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2123 // Is `mut self` `n` tokens ahead?
2124 let is_isolated_mut_self = |this: &Self, n| {
2125 this.is_keyword_ahead(n, &[kw::Mut])
2126 && is_isolated_self(this, n + 1)
2128 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2129 let parse_self_possibly_typed = |this: &mut Self, m| {
2130 let eself_ident = expect_self_ident(this);
2131 let eself_hi = this.prev_span;
2132 let eself = if this.eat(&token::Colon) {
2133 SelfKind::Explicit(this.parse_ty()?, m)
2137 Ok((eself, eself_ident, eself_hi))
2139 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2140 let recover_self_ptr = |this: &mut Self| {
2141 let msg = "cannot pass `self` by raw pointer";
2142 let span = this.token.span;
2143 this.struct_span_err(span, msg)
2144 .span_label(span, msg)
2147 Ok((SelfKind::Value(Mutability::Immutable), expect_self_ident(this), this.prev_span))
2150 // Parse optional `self` parameter of a method.
2151 // Only a limited set of initial token sequences is considered `self` parameters; anything
2152 // else is parsed as a normal function parameter list, so some lookahead is required.
2153 let eself_lo = self.token.span;
2154 let (eself, eself_ident, eself_hi) = match self.token.kind {
2155 token::BinOp(token::And) => {
2156 let eself = if is_isolated_self(self, 1) {
2159 SelfKind::Region(None, Mutability::Immutable)
2160 } else if is_isolated_mut_self(self, 1) {
2164 SelfKind::Region(None, Mutability::Mutable)
2165 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2168 let lt = self.expect_lifetime();
2169 SelfKind::Region(Some(lt), Mutability::Immutable)
2170 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2173 let lt = self.expect_lifetime();
2175 SelfKind::Region(Some(lt), Mutability::Mutable)
2180 (eself, expect_self_ident(self), self.prev_span)
2183 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2185 recover_self_ptr(self)?
2187 // `*mut self` and `*const self`
2188 token::BinOp(token::Star) if
2189 self.look_ahead(1, |t| t.is_mutability())
2190 && is_isolated_self(self, 2) =>
2194 recover_self_ptr(self)?
2196 // `self` and `self: TYPE`
2197 token::Ident(..) if is_isolated_self(self, 0) => {
2198 parse_self_possibly_typed(self, Mutability::Immutable)?
2200 // `mut self` and `mut self: TYPE`
2201 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2203 parse_self_possibly_typed(self, Mutability::Mutable)?
2205 _ => return Ok(None),
2208 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2209 Ok(Some(Param::from_self(ThinVec::default(), eself, eself_ident)))
2212 fn is_named_param(&self) -> bool {
2213 let offset = match self.token.kind {
2214 token::Interpolated(ref nt) => match **nt {
2215 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2218 token::BinOp(token::And) | token::AndAnd => 1,
2219 _ if self.token.is_keyword(kw::Mut) => 1,
2223 self.look_ahead(offset, |t| t.is_ident()) &&
2224 self.look_ahead(offset + 1, |t| t == &token::Colon)
2227 fn recover_first_param(&mut self) -> &'static str {
2228 match self.parse_outer_attributes()
2229 .and_then(|_| self.parse_self_param())
2230 .map_err(|mut e| e.cancel())
2232 Ok(Some(_)) => "method",