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;
8 use rustc_ast::token::{self, TokenKind};
9 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
10 use rustc_ast::{self as ast, AttrStyle, AttrVec, Attribute, DUMMY_NODE_ID};
11 use rustc_ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind, Mod};
12 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
13 use rustc_ast::{BindingMode, Block, FnDecl, FnSig, Param, SelfKind};
14 use rustc_ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
15 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
16 use rustc_ast::{MacArgs, MacCall, MacDelimiter};
17 use rustc_ast_pretty::pprust;
18 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
19 use rustc_span::edition::Edition;
20 use rustc_span::source_map::{self, Span};
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
23 use std::convert::TryFrom;
28 /// Parses a source module as a crate. This is the main entry point for the parser.
29 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
30 let lo = self.token.span;
31 let (module, attrs) = self.parse_mod(&token::Eof)?;
32 let span = lo.to(self.token.span);
33 let proc_macros = Vec::new(); // Filled in by `proc_macro_harness::inject()`.
34 Ok(ast::Crate { attrs, module, span, proc_macros })
37 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
38 fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
39 let id = self.parse_ident()?;
40 let (module, mut inner_attrs) = if self.eat(&token::Semi) {
43 self.expect(&token::OpenDelim(token::Brace))?;
44 self.parse_mod(&token::CloseDelim(token::Brace))?
46 attrs.append(&mut inner_attrs);
47 Ok((id, ItemKind::Mod(module)))
50 /// Parses the contents of a module (inner attributes followed by module items).
51 pub fn parse_mod(&mut self, term: &TokenKind) -> PResult<'a, (Mod, Vec<Attribute>)> {
52 let lo = self.token.span;
53 let attrs = self.parse_inner_attributes()?;
54 let module = self.parse_mod_items(term, lo)?;
58 /// Given a termination token, parses all of the items in a module.
59 fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
60 let mut items = vec![];
61 while let Some(item) = self.parse_item()? {
63 self.maybe_consume_incorrect_semicolon(&items);
67 let token_str = super::token_descr(&self.token);
68 if !self.maybe_consume_incorrect_semicolon(&items) {
69 let msg = &format!("expected item, found {}", token_str);
70 let mut err = self.struct_span_err(self.token.span, msg);
71 err.span_label(self.token.span, "expected item");
76 let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_token.span };
78 Ok(Mod { inner: inner_lo.to(hi), items, inline: true })
82 pub(super) type ItemInfo = (Ident, ItemKind);
85 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
86 self.parse_item_(|_| true).map(|i| i.map(P))
89 fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
90 let attrs = self.parse_outer_attributes()?;
91 self.parse_item_common(attrs, true, false, req_name)
94 pub(super) fn parse_item_common(
96 mut attrs: Vec<Attribute>,
100 ) -> PResult<'a, Option<Item>> {
101 maybe_whole!(self, NtItem, |item| {
103 mem::swap(&mut item.attrs, &mut attrs);
104 item.attrs.extend(attrs);
105 Some(item.into_inner())
108 let mut unclosed_delims = vec![];
109 let has_attrs = !attrs.is_empty();
110 let parse_item = |this: &mut Self| {
111 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
112 unclosed_delims.append(&mut this.unclosed_delims);
116 let (mut item, tokens) = if has_attrs {
117 let (item, tokens) = self.collect_tokens(parse_item)?;
120 (parse_item(self)?, None)
123 self.unclosed_delims.append(&mut unclosed_delims);
125 // Once we've parsed an item and recorded the tokens we got while
126 // parsing we may want to store `tokens` into the item we're about to
127 // return. Note, though, that we specifically didn't capture tokens
128 // related to outer attributes. The `tokens` field here may later be
129 // used with procedural macros to convert this item back into a token
130 // stream, but during expansion we may be removing attributes as we go
133 // If we've got inner attributes then the `tokens` we've got above holds
134 // these inner attributes. If an inner attribute is expanded we won't
135 // actually remove it from the token stream, so we'll just keep yielding
136 // it (bad!). To work around this case for now we just avoid recording
137 // `tokens` if we detect any inner attributes. This should help keep
138 // expansion correct, but we should fix this bug one day!
139 if let Some(tokens) = tokens {
140 if let Some(item) = &mut item {
141 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
142 item.tokens = Some(tokens);
149 fn parse_item_common_(
151 mut attrs: Vec<Attribute>,
155 ) -> PResult<'a, Option<Item>> {
156 let lo = self.token.span;
157 let vis = self.parse_visibility(FollowedByType::No)?;
158 let mut def = self.parse_defaultness();
159 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
160 if let Some((ident, kind)) = kind {
161 self.error_on_unconsumed_default(def, &kind);
162 let span = lo.to(self.prev_token.span);
163 let id = DUMMY_NODE_ID;
164 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
165 return Ok(Some(item));
168 // At this point, we have failed to parse an item.
169 self.error_on_unmatched_vis(&vis);
170 self.error_on_unmatched_defaultness(def);
172 self.recover_attrs_no_item(&attrs)?;
177 /// Error in-case a non-inherited visibility was parsed but no item followed.
178 fn error_on_unmatched_vis(&self, vis: &Visibility) {
179 if let VisibilityKind::Inherited = vis.node {
182 let vs = pprust::vis_to_string(&vis);
183 let vs = vs.trim_end();
184 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
185 .span_label(vis.span, "the visibility")
186 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
190 /// Error in-case a `default` was parsed but no item followed.
191 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
192 if let Defaultness::Default(sp) = def {
193 self.struct_span_err(sp, "`default` is not followed by an item")
194 .span_label(sp, "the `default` qualifier")
195 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
200 /// Error in-case `default` was parsed in an in-appropriate context.
201 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
202 if let Defaultness::Default(span) = def {
203 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
204 self.struct_span_err(span, &msg)
205 .span_label(span, "`default` because of this")
206 .note("only associated `fn`, `const`, and `type` items can be `default`")
211 /// Parses one of the items allowed by the flags.
214 attrs: &mut Vec<Attribute>,
215 macros_allowed: bool,
218 def: &mut Defaultness,
220 ) -> PResult<'a, Option<ItemInfo>> {
221 let mut def = || mem::replace(def, Defaultness::Final);
223 let info = if self.eat_keyword(kw::Use) {
225 let tree = self.parse_use_tree()?;
227 (Ident::invalid(), ItemKind::Use(P(tree)))
228 } else if self.check_fn_front_matter() {
230 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name)?;
231 (ident, ItemKind::Fn(def(), sig, generics, body))
232 } else if self.eat_keyword(kw::Extern) {
233 if self.eat_keyword(kw::Crate) {
235 self.parse_item_extern_crate()?
238 self.parse_item_foreign_mod(attrs)?
240 } else if self.is_static_global() {
242 self.bump(); // `static`
243 let m = self.parse_mutability();
244 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
245 (ident, ItemKind::Static(ty, m, expr))
246 } else if let Const::Yes(const_span) = self.parse_constness() {
248 self.recover_const_mut(const_span);
249 let (ident, ty, expr) = self.parse_item_global(None)?;
250 (ident, ItemKind::Const(def(), ty, expr))
251 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
253 self.parse_item_trait(attrs, lo)?
254 } else if self.check_keyword(kw::Impl)
255 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
258 self.parse_item_impl(attrs, def())?
259 } else if self.eat_keyword(kw::Mod) {
261 self.parse_item_mod(attrs)?
262 } else if self.eat_keyword(kw::Type) {
264 self.parse_type_alias(def())?
265 } else if self.eat_keyword(kw::Enum) {
267 self.parse_item_enum()?
268 } else if self.eat_keyword(kw::Struct) {
270 self.parse_item_struct()?
271 } else if self.is_kw_followed_by_ident(kw::Union) {
273 self.bump(); // `union`
274 self.parse_item_union()?
275 } else if self.eat_keyword(kw::Macro) {
277 self.parse_item_decl_macro(lo)?
278 } else if self.is_macro_rules_item() {
280 self.parse_item_macro_rules(vis)?
281 } else if vis.node.is_pub() && self.isnt_macro_invocation() {
282 self.recover_missing_kw_before_item()?;
284 } else if macros_allowed && self.check_path() {
285 // MACRO INVOCATION ITEM
286 (Ident::invalid(), ItemKind::MacCall(self.parse_item_macro(vis)?))
293 /// When parsing a statement, would the start of a path be an item?
294 pub(super) fn is_path_start_item(&mut self) -> bool {
295 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
296 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
297 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
298 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
299 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
302 /// Are we sure this could not possibly be a macro invocation?
303 fn isnt_macro_invocation(&mut self) -> bool {
304 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
307 /// Recover on encountering a struct or method definition where the user
308 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
309 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
310 // Space between `pub` keyword and the identifier
313 // ^^^ `sp` points here
314 let sp = self.prev_token.span.between(self.token.span);
315 let full_sp = self.prev_token.span.to(self.token.span);
316 let ident_sp = self.token.span;
317 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
318 // possible public struct definition where `struct` was forgotten
319 let ident = self.parse_ident().unwrap();
320 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
321 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
322 err.span_suggestion_short(
326 Applicability::MaybeIncorrect, // speculative
329 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
330 let ident = self.parse_ident().unwrap();
332 let kw_name = self.recover_first_param();
333 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
334 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
335 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
337 ("fn", kw_name, false)
338 } else if self.check(&token::OpenDelim(token::Brace)) {
340 ("fn", kw_name, false)
341 } else if self.check(&token::Colon) {
345 ("fn` or `struct", "function or struct", true)
348 let msg = format!("missing `{}` for {} definition", kw, kw_name);
349 let mut err = self.struct_span_err(sp, &msg);
351 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
353 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
354 err.span_suggestion_short(
358 Applicability::MachineApplicable,
361 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
364 "if you meant to call a macro, try",
365 format!("{}!", snippet),
366 // this is the `ambiguous` conditional branch
367 Applicability::MaybeIncorrect,
371 "if you meant to call a macro, remove the `pub` \
372 and add a trailing `!` after the identifier",
377 } else if self.look_ahead(1, |t| *t == token::Lt) {
378 let ident = self.parse_ident().unwrap();
379 self.eat_to_tokens(&[&token::Gt]);
381 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
382 ("fn", self.recover_first_param(), false)
383 } else if self.check(&token::OpenDelim(token::Brace)) {
384 ("struct", "struct", false)
386 ("fn` or `struct", "function or struct", true)
388 let msg = format!("missing `{}` for {} definition", kw, kw_name);
389 let mut err = self.struct_span_err(sp, &msg);
391 err.span_suggestion_short(
393 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
395 Applicability::MachineApplicable,
404 /// Parses an item macro, e.g., `item!();`.
405 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
406 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
407 self.expect(&token::Not)?; // `!`
408 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
409 self.eat_semi_for_macro_if_needed(&args);
410 self.complain_if_pub_macro(vis, false);
411 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
414 /// Recover if we parsed attributes and expected an item but there was none.
415 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
416 let (start, end) = match attrs {
418 [x0 @ xn] | [x0, .., xn] => (x0, xn),
420 let msg = if end.is_doc_comment() {
421 "expected item after doc comment"
423 "expected item after attributes"
425 let mut err = self.struct_span_err(end.span, msg);
426 if end.is_doc_comment() {
427 err.span_label(end.span, "this doc comment doesn't document anything");
429 if let [.., penultimate, _] = attrs {
430 err.span_label(start.span.to(penultimate.span), "other attributes here");
435 fn is_async_fn(&self) -> bool {
436 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
439 fn parse_polarity(&mut self) -> ast::ImplPolarity {
440 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
441 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
443 ast::ImplPolarity::Negative(self.prev_token.span)
445 ast::ImplPolarity::Positive
449 /// Parses an implementation item.
452 /// impl<'a, T> TYPE { /* impl items */ }
453 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
454 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
455 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
458 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
460 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
461 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
465 attrs: &mut Vec<Attribute>,
466 defaultness: Defaultness,
467 ) -> PResult<'a, ItemInfo> {
468 let unsafety = self.parse_unsafety();
469 self.expect_keyword(kw::Impl)?;
471 // First, parse generic parameters if necessary.
472 let mut generics = if self.choose_generics_over_qpath(0) {
473 self.parse_generics()?
475 let mut generics = Generics::default();
477 // /\ this is where `generics.span` should point when there are no type params.
478 generics.span = self.prev_token.span.shrink_to_hi();
482 let constness = self.parse_constness();
483 if let Const::Yes(span) = constness {
484 self.sess.gated_spans.gate(sym::const_trait_impl, span);
487 let polarity = self.parse_polarity();
489 // Parse both types and traits as a type, then reinterpret if necessary.
490 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
491 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
493 let span = self.prev_token.span.between(self.token.span);
494 self.struct_span_err(span, "missing trait in a trait impl").emit();
495 P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID })
500 // If `for` is missing we try to recover.
501 let has_for = self.eat_keyword(kw::For);
502 let missing_for_span = self.prev_token.span.between(self.token.span);
504 let ty_second = if self.token == token::DotDot {
505 // We need to report this error after `cfg` expansion for compatibility reasons
506 self.bump(); // `..`, do not add it to expected tokens
507 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
508 } else if has_for || self.token.can_begin_type() {
509 Some(self.parse_ty()?)
514 generics.where_clause = self.parse_where_clause()?;
516 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
518 let item_kind = match ty_second {
520 // impl Trait for Type
522 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
523 .span_suggestion_short(
527 Applicability::MachineApplicable,
532 let ty_first = ty_first.into_inner();
533 let path = match ty_first.kind {
534 // This notably includes paths passed through `ty` macro fragments (#46438).
535 TyKind::Path(None, path) => path,
537 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
538 err_path(ty_first.span)
541 let trait_ref = TraitRef { path, ref_id: ty_first.id };
549 of_trait: Some(trait_ref),
569 Ok((Ident::invalid(), item_kind))
572 fn parse_item_list<T>(
574 attrs: &mut Vec<Attribute>,
575 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
576 ) -> PResult<'a, Vec<T>> {
577 let open_brace_span = self.token.span;
578 self.expect(&token::OpenDelim(token::Brace))?;
579 attrs.append(&mut self.parse_inner_attributes()?);
581 let mut items = Vec::new();
582 while !self.eat(&token::CloseDelim(token::Brace)) {
583 if self.recover_doc_comment_before_brace() {
586 match parse_item(self) {
588 // We have to bail or we'll potentially never make progress.
589 let non_item_span = self.token.span;
590 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
591 self.struct_span_err(non_item_span, "non-item in item list")
592 .span_label(open_brace_span, "item list starts here")
593 .span_label(non_item_span, "non-item starts here")
594 .span_label(self.prev_token.span, "item list ends here")
598 Ok(Some(item)) => items.extend(item),
600 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
601 err.span_label(open_brace_span, "while parsing this item list starting here")
602 .span_label(self.prev_token.span, "the item list ends here")
611 /// Recover on a doc comment before `}`.
612 fn recover_doc_comment_before_brace(&mut self) -> bool {
613 if let token::DocComment(..) = self.token.kind {
614 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
619 "found a documentation comment that doesn't document anything",
621 .span_label(self.token.span, "this doc comment doesn't document anything")
623 "doc comments must come before what they document, maybe a \
624 comment was intended with `//`?",
634 /// Parses defaultness (i.e., `default` or nothing).
635 fn parse_defaultness(&mut self) -> Defaultness {
636 // We are interested in `default` followed by another identifier.
637 // However, we must avoid keywords that occur as binary operators.
638 // Currently, the only applicable keyword is `as` (`default as Ty`).
639 if self.check_keyword(kw::Default)
640 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
642 self.bump(); // `default`
643 Defaultness::Default(self.prev_token.uninterpolated_span())
649 /// Is this an `(unsafe auto? | auto) trait` item?
650 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
652 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
654 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
657 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
658 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
659 let unsafety = self.parse_unsafety();
660 // Parse optional `auto` prefix.
661 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
663 self.expect_keyword(kw::Trait)?;
664 let ident = self.parse_ident()?;
665 let mut tps = self.parse_generics()?;
667 // Parse optional colon and supertrait bounds.
668 let had_colon = self.eat(&token::Colon);
669 let span_at_colon = self.prev_token.span;
670 let bounds = if had_colon {
671 self.parse_generic_bounds(Some(self.prev_token.span))?
676 let span_before_eq = self.prev_token.span;
677 if self.eat(&token::Eq) {
678 // It's a trait alias.
680 let span = span_at_colon.to(span_before_eq);
681 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
684 let bounds = self.parse_generic_bounds(None)?;
685 tps.where_clause = self.parse_where_clause()?;
688 let whole_span = lo.to(self.prev_token.span);
689 if is_auto == IsAuto::Yes {
690 let msg = "trait aliases cannot be `auto`";
691 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
693 if let Unsafe::Yes(_) = unsafety {
694 let msg = "trait aliases cannot be `unsafe`";
695 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
698 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
700 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
702 // It's a normal trait.
703 tps.where_clause = self.parse_where_clause()?;
704 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
705 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
709 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
710 self.parse_assoc_item(|_| true)
713 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
714 self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
717 /// Parses associated items.
718 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
719 Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
720 let kind = match AssocItemKind::try_from(kind) {
722 Err(kind) => match kind {
723 ItemKind::Static(a, _, b) => {
724 self.struct_span_err(span, "associated `static` items are not allowed")
726 AssocItemKind::Const(Defaultness::Final, a, b)
728 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
731 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
735 /// Parses a `type` alias with the following grammar:
737 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
739 /// The `"type"` has already been eaten.
740 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
741 let ident = self.parse_ident()?;
742 let mut generics = self.parse_generics()?;
744 // Parse optional colon and param bounds.
746 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
747 generics.where_clause = self.parse_where_clause()?;
749 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
752 Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
755 /// Parses a `UseTree`.
758 /// USE_TREE = [`::`] `*` |
759 /// [`::`] `{` USE_TREE_LIST `}` |
761 /// PATH `::` `{` USE_TREE_LIST `}` |
762 /// PATH [`as` IDENT]
764 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
765 let lo = self.token.span;
767 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
768 let kind = if self.check(&token::OpenDelim(token::Brace))
769 || self.check(&token::BinOp(token::Star))
770 || self.is_import_coupler()
772 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
773 let mod_sep_ctxt = self.token.span.ctxt();
774 if self.eat(&token::ModSep) {
777 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
780 self.parse_use_tree_glob_or_nested()?
782 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
783 prefix = self.parse_path(PathStyle::Mod)?;
785 if self.eat(&token::ModSep) {
786 self.parse_use_tree_glob_or_nested()?
788 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
792 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
795 /// Parses `*` or `{...}`.
796 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
797 Ok(if self.eat(&token::BinOp(token::Star)) {
800 UseTreeKind::Nested(self.parse_use_tree_list()?)
804 /// Parses a `UseTreeKind::Nested(list)`.
807 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
809 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
810 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
814 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
815 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
818 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
819 match self.token.ident() {
820 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
824 _ => self.parse_ident(),
828 /// Parses `extern crate` links.
833 /// extern crate foo;
834 /// extern crate bar as foo;
836 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
837 // Accept `extern crate name-like-this` for better diagnostics
838 let orig_name = self.parse_crate_name_with_dashes()?;
839 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
840 (rename, Some(orig_name.name))
845 Ok((item_name, ItemKind::ExternCrate(orig_name)))
848 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
849 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
850 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
852 let mut ident = if self.token.is_keyword(kw::SelfLower) {
853 self.parse_path_segment_ident()
857 let mut idents = vec![];
858 let mut replacement = vec![];
859 let mut fixed_crate_name = false;
860 // Accept `extern crate name-like-this` for better diagnostics.
861 let dash = token::BinOp(token::BinOpToken::Minus);
862 if self.token == dash {
863 // Do not include `-` as part of the expected tokens list.
864 while self.eat(&dash) {
865 fixed_crate_name = true;
866 replacement.push((self.prev_token.span, "_".to_string()));
867 idents.push(self.parse_ident()?);
870 if fixed_crate_name {
871 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
872 let mut fixed_name = format!("{}", ident.name);
874 fixed_name.push_str(&format!("_{}", part.name));
876 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
878 self.struct_span_err(fixed_name_sp, error_msg)
879 .span_label(fixed_name_sp, "dash-separated idents are not valid")
880 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
886 /// Parses `extern` for foreign ABIs modules.
888 /// `extern` is expected to have been consumed before calling this method.
892 /// ```ignore (only-for-syntax-highlight)
896 fn parse_item_foreign_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
897 let abi = self.parse_abi(); // ABI?
898 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
899 let module = ast::ForeignMod { abi, items };
900 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
903 /// Parses a foreign item (one in an `extern { ... }` block).
904 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
905 Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
906 let kind = match ForeignItemKind::try_from(kind) {
908 Err(kind) => match kind {
909 ItemKind::Const(_, a, b) => {
910 self.error_on_foreign_const(span, ident);
911 ForeignItemKind::Static(a, Mutability::Not, b)
913 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
916 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
920 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
921 let span = self.sess.source_map().guess_head_span(span);
922 let descr = kind.descr();
923 self.struct_span_err(span, &format!("{} is not supported in {}", descr, ctx))
924 .help(&format!("consider moving the {} out to a nearby module scope", descr))
929 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
930 self.struct_span_err(ident.span, "extern items cannot be `const`")
932 span.with_hi(ident.span.lo()),
933 "try using a static value",
934 "static ".to_string(),
935 Applicability::MachineApplicable,
937 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
941 fn is_static_global(&mut self) -> bool {
942 if self.check_keyword(kw::Static) {
943 // Check if this could be a closure.
944 !self.look_ahead(1, |token| {
945 if token.is_keyword(kw::Move) {
949 token::BinOp(token::Or) | token::OrOr => true,
958 /// Recover on `const mut` with `const` already eaten.
959 fn recover_const_mut(&mut self, const_span: Span) {
960 if self.eat_keyword(kw::Mut) {
961 let span = self.prev_token.span;
962 self.struct_span_err(span, "const globals cannot be mutable")
963 .span_label(span, "cannot be mutable")
966 "you might want to declare a static instead",
968 Applicability::MaybeIncorrect,
974 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
975 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
977 /// When `m` is `"const"`, `$ident` may also be `"_"`.
978 fn parse_item_global(
980 m: Option<Mutability>,
981 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
982 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
984 // Parse the type of a `const` or `static mut?` item.
985 // That is, the `":" $ty` fragment.
986 let ty = if self.eat(&token::Colon) {
989 self.recover_missing_const_type(id, m)
992 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
997 /// We were supposed to parse `:` but the `:` was missing.
998 /// This means that the type is missing.
999 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1000 // Construct the error and stash it away with the hope
1001 // that typeck will later enrich the error with a type.
1002 let kind = match m {
1003 Some(Mutability::Mut) => "static mut",
1004 Some(Mutability::Not) => "static",
1007 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1008 err.span_suggestion(
1010 "provide a type for the item",
1011 format!("{}: <type>", id),
1012 Applicability::HasPlaceholders,
1014 err.stash(id.span, StashKey::ItemNoType);
1016 // The user intended that the type be inferred,
1017 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1018 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID })
1021 /// Parses an enum declaration.
1022 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1023 let id = self.parse_ident()?;
1024 let mut generics = self.parse_generics()?;
1025 generics.where_clause = self.parse_where_clause()?;
1028 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1029 self.recover_stmt();
1033 let enum_definition =
1034 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1035 Ok((id, ItemKind::Enum(enum_definition, generics)))
1038 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1039 let variant_attrs = self.parse_outer_attributes()?;
1040 let vlo = self.token.span;
1042 let vis = self.parse_visibility(FollowedByType::No)?;
1043 if !self.recover_nested_adt_item(kw::Enum)? {
1046 let ident = self.parse_ident()?;
1048 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1049 // Parse a struct variant.
1050 let (fields, recovered) = self.parse_record_struct_body()?;
1051 VariantData::Struct(fields, recovered)
1052 } else if self.check(&token::OpenDelim(token::Paren)) {
1053 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1055 VariantData::Unit(DUMMY_NODE_ID)
1059 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1061 let vr = ast::Variant {
1065 attrs: variant_attrs,
1068 span: vlo.to(self.prev_token.span),
1069 is_placeholder: false,
1075 /// Parses `struct Foo { ... }`.
1076 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1077 let class_name = self.parse_ident()?;
1079 let mut generics = self.parse_generics()?;
1081 // There is a special case worth noting here, as reported in issue #17904.
1082 // If we are parsing a tuple struct it is the case that the where clause
1083 // should follow the field list. Like so:
1085 // struct Foo<T>(T) where T: Copy;
1087 // If we are parsing a normal record-style struct it is the case
1088 // that the where clause comes before the body, and after the generics.
1089 // So if we look ahead and see a brace or a where-clause we begin
1090 // parsing a record style struct.
1092 // Otherwise if we look ahead and see a paren we parse a tuple-style
1095 let vdata = if self.token.is_keyword(kw::Where) {
1096 generics.where_clause = self.parse_where_clause()?;
1097 if self.eat(&token::Semi) {
1098 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1099 VariantData::Unit(DUMMY_NODE_ID)
1101 // If we see: `struct Foo<T> where T: Copy { ... }`
1102 let (fields, recovered) = self.parse_record_struct_body()?;
1103 VariantData::Struct(fields, recovered)
1105 // No `where` so: `struct Foo<T>;`
1106 } else if self.eat(&token::Semi) {
1107 VariantData::Unit(DUMMY_NODE_ID)
1108 // Record-style struct definition
1109 } else if self.token == token::OpenDelim(token::Brace) {
1110 let (fields, recovered) = self.parse_record_struct_body()?;
1111 VariantData::Struct(fields, recovered)
1112 // Tuple-style struct definition with optional where-clause.
1113 } else if self.token == token::OpenDelim(token::Paren) {
1114 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1115 generics.where_clause = self.parse_where_clause()?;
1116 self.expect_semi()?;
1119 let token_str = super::token_descr(&self.token);
1121 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1124 let mut err = self.struct_span_err(self.token.span, msg);
1125 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1129 Ok((class_name, ItemKind::Struct(vdata, generics)))
1132 /// Parses `union Foo { ... }`.
1133 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1134 let class_name = self.parse_ident()?;
1136 let mut generics = self.parse_generics()?;
1138 let vdata = if self.token.is_keyword(kw::Where) {
1139 generics.where_clause = self.parse_where_clause()?;
1140 let (fields, recovered) = self.parse_record_struct_body()?;
1141 VariantData::Struct(fields, recovered)
1142 } else if self.token == token::OpenDelim(token::Brace) {
1143 let (fields, recovered) = self.parse_record_struct_body()?;
1144 VariantData::Struct(fields, recovered)
1146 let token_str = super::token_descr(&self.token);
1147 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1148 let mut err = self.struct_span_err(self.token.span, msg);
1149 err.span_label(self.token.span, "expected `where` or `{` after union name");
1153 Ok((class_name, ItemKind::Union(vdata, generics)))
1156 fn parse_record_struct_body(
1158 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1159 let mut fields = Vec::new();
1160 let mut recovered = false;
1161 if self.eat(&token::OpenDelim(token::Brace)) {
1162 while self.token != token::CloseDelim(token::Brace) {
1163 let field = self.parse_struct_decl_field().map_err(|e| {
1164 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1169 Ok(field) => fields.push(field),
1176 self.eat(&token::CloseDelim(token::Brace));
1178 let token_str = super::token_descr(&self.token);
1179 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1180 let mut err = self.struct_span_err(self.token.span, msg);
1181 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1185 Ok((fields, recovered))
1188 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1189 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1190 // Unit like structs are handled in parse_item_struct function
1191 self.parse_paren_comma_seq(|p| {
1192 let attrs = p.parse_outer_attributes()?;
1193 let lo = p.token.span;
1194 let vis = p.parse_visibility(FollowedByType::Yes)?;
1195 let ty = p.parse_ty()?;
1197 span: lo.to(ty.span),
1203 is_placeholder: false,
1209 /// Parses an element of a struct declaration.
1210 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1211 let attrs = self.parse_outer_attributes()?;
1212 let lo = self.token.span;
1213 let vis = self.parse_visibility(FollowedByType::No)?;
1214 self.parse_single_struct_field(lo, vis, attrs)
1217 /// Parses a structure field declaration.
1218 fn parse_single_struct_field(
1222 attrs: Vec<Attribute>,
1223 ) -> PResult<'a, StructField> {
1224 let mut seen_comma: bool = false;
1225 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1226 if self.token == token::Comma {
1229 match self.token.kind {
1233 token::CloseDelim(token::Brace) => {}
1234 token::DocComment(..) => {
1235 let previous_span = self.prev_token.span;
1236 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1237 self.bump(); // consume the doc comment
1238 let comma_after_doc_seen = self.eat(&token::Comma);
1239 // `seen_comma` is always false, because we are inside doc block
1240 // condition is here to make code more readable
1241 if !seen_comma && comma_after_doc_seen {
1244 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1248 let sp = self.sess.source_map().next_point(previous_span);
1249 err.span_suggestion(
1251 "missing comma here",
1253 Applicability::MachineApplicable,
1260 let sp = self.prev_token.span.shrink_to_hi();
1261 let mut err = self.struct_span_err(
1263 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1266 // Try to recover extra trailing angle brackets
1267 let mut recovered = false;
1268 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1269 if let Some(last_segment) = segments.last() {
1270 recovered = self.check_trailing_angle_brackets(
1272 &[&token::Comma, &token::CloseDelim(token::Brace)],
1275 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1277 self.eat(&token::Comma);
1278 // `check_trailing_angle_brackets` already emitted a nicer error
1284 if self.token.is_ident() {
1285 // This is likely another field; emit the diagnostic and keep going
1286 err.span_suggestion(
1288 "try adding a comma",
1290 Applicability::MachineApplicable,
1297 // Make sure an error was emitted (either by recovering an angle bracket,
1298 // or by finding an identifier as the next token), since we're
1299 // going to continue parsing
1300 assert!(self.sess.span_diagnostic.has_errors());
1309 /// Parses a structure field.
1310 fn parse_name_and_ty(
1314 attrs: Vec<Attribute>,
1315 ) -> PResult<'a, StructField> {
1316 let name = self.parse_ident_common(false)?;
1317 self.expect(&token::Colon)?;
1318 let ty = self.parse_ty()?;
1320 span: lo.to(self.prev_token.span),
1326 is_placeholder: false,
1330 /// Parses a declarative macro 2.0 definition.
1331 /// The `macro` keyword has already been parsed.
1333 /// MacBody = "{" TOKEN_STREAM "}" ;
1334 /// MacParams = "(" TOKEN_STREAM ")" ;
1335 /// DeclMac = "macro" Ident MacParams? MacBody ;
1337 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1338 let ident = self.parse_ident()?;
1339 let body = if self.check(&token::OpenDelim(token::Brace)) {
1340 self.parse_mac_args()? // `MacBody`
1341 } else if self.check(&token::OpenDelim(token::Paren)) {
1342 let params = self.parse_token_tree(); // `MacParams`
1343 let pspan = params.span();
1344 if !self.check(&token::OpenDelim(token::Brace)) {
1345 return self.unexpected();
1347 let body = self.parse_token_tree(); // `MacBody`
1348 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1349 let bspan = body.span();
1350 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1351 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1352 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1353 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1355 return self.unexpected();
1358 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1359 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1362 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1363 fn is_macro_rules_item(&mut self) -> bool {
1364 self.check_keyword(kw::MacroRules)
1365 && self.look_ahead(1, |t| *t == token::Not)
1366 && self.look_ahead(2, |t| t.is_ident())
1369 /// Parses a `macro_rules! foo { ... }` declarative macro.
1370 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1371 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1372 self.expect(&token::Not)?; // `!`
1374 let ident = self.parse_ident()?;
1375 let body = self.parse_mac_args()?;
1376 self.eat_semi_for_macro_if_needed(&body);
1377 self.complain_if_pub_macro(vis, true);
1379 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1382 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1383 /// If that's not the case, emit an error.
1384 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1385 if let VisibilityKind::Inherited = vis.node {
1389 let vstr = pprust::vis_to_string(vis);
1390 let vstr = vstr.trim_end();
1392 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1393 self.struct_span_err(vis.span, &msg)
1396 "try exporting the macro",
1397 "#[macro_export]".to_owned(),
1398 Applicability::MaybeIncorrect, // speculative
1402 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1405 "remove the visibility",
1407 Applicability::MachineApplicable,
1409 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1414 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1415 if args.need_semicolon() && !self.eat(&token::Semi) {
1416 self.report_invalid_macro_expansion_item(args);
1420 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1421 let span = args.span().expect("undelimited macro call");
1422 let mut err = self.struct_span_err(
1424 "macros that expand to items must be delimited with braces or followed by a semicolon",
1426 if self.unclosed_delims.is_empty() {
1427 let DelimSpan { open, close } = match args {
1428 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1429 MacArgs::Delimited(dspan, ..) => *dspan,
1431 err.multipart_suggestion(
1432 "change the delimiters to curly braces",
1433 vec![(open, "{".to_string()), (close, '}'.to_string())],
1434 Applicability::MaybeIncorrect,
1437 err.span_suggestion(
1439 "change the delimiters to curly braces",
1440 " { /* items */ }".to_string(),
1441 Applicability::HasPlaceholders,
1444 err.span_suggestion(
1445 span.shrink_to_hi(),
1448 Applicability::MaybeIncorrect,
1453 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1454 /// it is, we try to parse the item and report error about nested types.
1455 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1456 if (self.token.is_keyword(kw::Enum)
1457 || self.token.is_keyword(kw::Struct)
1458 || self.token.is_keyword(kw::Union))
1459 && self.look_ahead(1, |t| t.is_ident())
1461 let kw_token = self.token.clone();
1462 let kw_str = pprust::token_to_string(&kw_token);
1463 let item = self.parse_item()?;
1465 self.struct_span_err(
1467 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1471 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1473 Applicability::MaybeIncorrect,
1476 // We successfully parsed the item but we must inform the caller about nested problem.
1483 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1485 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1486 type ReqName = fn(Edition) -> bool;
1488 /// Parsing of functions and methods.
1489 impl<'a> Parser<'a> {
1490 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1493 attrs: &mut Vec<Attribute>,
1495 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1496 let header = self.parse_fn_front_matter()?; // `const ... fn`
1497 let ident = self.parse_ident()?; // `foo`
1498 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1499 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1500 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1501 let body = self.parse_fn_body(attrs)?; // `;` or `{ ... }`.
1502 Ok((ident, FnSig { header, decl }, generics, body))
1505 /// Parse the "body" of a function.
1506 /// This can either be `;` when there's no body,
1507 /// or e.g. a block when the function is a provided one.
1508 fn parse_fn_body(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, Option<P<Block>>> {
1509 let (inner_attrs, body) = if self.check(&token::Semi) {
1512 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1513 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1514 } else if self.token.kind == token::Eq {
1515 // Recover `fn foo() = $expr;`.
1517 let eq_sp = self.prev_token.span;
1518 let _ = self.parse_expr()?;
1519 self.expect_semi()?; // `;`
1520 let span = eq_sp.to(self.prev_token.span);
1521 self.struct_span_err(span, "function body cannot be `= expression;`")
1522 .multipart_suggestion(
1523 "surround the expression with `{` and `}` instead of `=` and `;`",
1524 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1525 Applicability::MachineApplicable,
1528 (Vec::new(), Some(self.mk_block_err(span)))
1530 return self.expected_semi_or_open_brace();
1532 attrs.extend(inner_attrs);
1536 /// Is the current token the start of an `FnHeader` / not a valid parse?
1537 pub(super) fn check_fn_front_matter(&mut self) -> bool {
1538 // We use an over-approximation here.
1539 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1540 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1541 self.check_keyword(kw::Fn) // Definitely an `fn`.
1542 // `$qual fn` or `$qual $qual`:
1543 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1544 && self.look_ahead(1, |t| {
1545 // ...qualified and then `fn`, e.g. `const fn`.
1546 t.is_keyword(kw::Fn)
1547 // Two qualifiers. This is enough. Due `async` we need to check that it's reserved.
1548 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name) && i.is_reserved())
1551 || self.check_keyword(kw::Extern)
1552 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1553 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1556 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1557 /// up to and including the `fn` keyword. The formal grammar is:
1560 /// Extern = "extern" StringLit ;
1561 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1562 /// FnFrontMatter = FnQual? "fn" ;
1564 pub(super) fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1565 let constness = self.parse_constness();
1566 let asyncness = self.parse_asyncness();
1567 let unsafety = self.parse_unsafety();
1568 let ext = self.parse_extern()?;
1570 if let Async::Yes { span, .. } = asyncness {
1571 self.ban_async_in_2015(span);
1574 if !self.eat_keyword(kw::Fn) {
1575 // It is possible for `expect_one_of` to recover given the contents of
1576 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1577 // account for this.
1578 if !self.expect_one_of(&[], &[])? {
1583 Ok(FnHeader { constness, unsafety, asyncness, ext })
1586 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1587 fn ban_async_in_2015(&self, span: Span) {
1588 if span.rust_2015() {
1589 let diag = self.diagnostic();
1590 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1591 .span_label(span, "to use `async fn`, switch to Rust 2018")
1592 .help("set `edition = \"2018\"` in `Cargo.toml`")
1593 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1598 /// Parses the parameter list and result type of a function declaration.
1599 pub(super) fn parse_fn_decl(
1602 ret_allow_plus: AllowPlus,
1603 ) -> PResult<'a, P<FnDecl>> {
1605 inputs: self.parse_fn_params(req_name)?,
1606 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1610 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1611 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1612 let mut first_param = true;
1613 // Parse the arguments, starting out with `self` being allowed...
1614 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1615 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1617 let lo = p.prev_token.span;
1618 // Skip every token until next possible arg or end.
1619 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1620 // Create a placeholder argument for proper arg count (issue #34264).
1621 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_token.span))))
1623 // ...now that we've parsed the first argument, `self` is no longer allowed.
1624 first_param = false;
1627 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1628 self.deduplicate_recovered_params_names(&mut params);
1632 /// Parses a single function parameter.
1634 /// - `self` is syntactically allowed when `first_param` holds.
1635 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1636 let lo = self.token.span;
1637 let attrs = self.parse_outer_attributes()?;
1639 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1640 if let Some(mut param) = self.parse_self_param()? {
1641 param.attrs = attrs.into();
1642 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1645 let is_name_required = match self.token.kind {
1646 token::DotDotDot => false,
1647 _ => req_name(self.token.span.edition()),
1649 let (pat, ty) = if is_name_required || self.is_named_param() {
1650 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1652 let pat = self.parse_fn_param_pat()?;
1653 if let Err(mut err) = self.expect(&token::Colon) {
1654 return if let Some(ident) =
1655 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1658 Ok(dummy_arg(ident))
1664 self.eat_incorrect_doc_comment_for_param_type();
1665 (pat, self.parse_ty_for_param()?)
1667 debug!("parse_param_general ident_to_pat");
1668 let parser_snapshot_before_ty = self.clone();
1669 self.eat_incorrect_doc_comment_for_param_type();
1670 let mut ty = self.parse_ty_for_param();
1672 && self.token != token::Comma
1673 && self.token != token::CloseDelim(token::Paren)
1675 // This wasn't actually a type, but a pattern looking like a type,
1676 // so we are going to rollback and re-parse for recovery.
1677 ty = self.unexpected();
1681 let ident = Ident::new(kw::Invalid, self.prev_token.span);
1682 let bm = BindingMode::ByValue(Mutability::Not);
1683 let pat = self.mk_pat_ident(ty.span, bm, ident);
1686 // If this is a C-variadic argument and we hit an error, return the error.
1687 Err(err) if self.token == token::DotDotDot => return Err(err),
1688 // Recover from attempting to parse the argument as a type without pattern.
1691 *self = parser_snapshot_before_ty;
1692 self.recover_arg_parse()?
1697 let span = lo.to(self.token.span);
1700 attrs: attrs.into(),
1701 id: ast::DUMMY_NODE_ID,
1702 is_placeholder: false,
1709 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1710 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1711 // Extract an identifier *after* having confirmed that the token is one.
1712 let expect_self_ident = |this: &mut Self| match this.token.ident() {
1713 Some((ident, false)) => {
1717 _ => unreachable!(),
1719 // Is `self` `n` tokens ahead?
1720 let is_isolated_self = |this: &Self, n| {
1721 this.is_keyword_ahead(n, &[kw::SelfLower])
1722 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1724 // Is `mut self` `n` tokens ahead?
1725 let is_isolated_mut_self =
1726 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1727 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1728 let parse_self_possibly_typed = |this: &mut Self, m| {
1729 let eself_ident = expect_self_ident(this);
1730 let eself_hi = this.prev_token.span;
1731 let eself = if this.eat(&token::Colon) {
1732 SelfKind::Explicit(this.parse_ty()?, m)
1736 Ok((eself, eself_ident, eself_hi))
1738 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1739 let recover_self_ptr = |this: &mut Self| {
1740 let msg = "cannot pass `self` by raw pointer";
1741 let span = this.token.span;
1742 this.struct_span_err(span, msg).span_label(span, msg).emit();
1744 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
1747 // Parse optional `self` parameter of a method.
1748 // Only a limited set of initial token sequences is considered `self` parameters; anything
1749 // else is parsed as a normal function parameter list, so some lookahead is required.
1750 let eself_lo = self.token.span;
1751 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
1752 token::BinOp(token::And) => {
1753 let eself = if is_isolated_self(self, 1) {
1756 SelfKind::Region(None, Mutability::Not)
1757 } else if is_isolated_mut_self(self, 1) {
1761 SelfKind::Region(None, Mutability::Mut)
1762 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1765 let lt = self.expect_lifetime();
1766 SelfKind::Region(Some(lt), Mutability::Not)
1767 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1770 let lt = self.expect_lifetime();
1772 SelfKind::Region(Some(lt), Mutability::Mut)
1777 (eself, expect_self_ident(self), self.prev_token.span)
1780 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1782 recover_self_ptr(self)?
1784 // `*mut self` and `*const self`
1785 token::BinOp(token::Star)
1786 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1790 recover_self_ptr(self)?
1792 // `self` and `self: TYPE`
1793 token::Ident(..) if is_isolated_self(self, 0) => {
1794 parse_self_possibly_typed(self, Mutability::Not)?
1796 // `mut self` and `mut self: TYPE`
1797 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1799 parse_self_possibly_typed(self, Mutability::Mut)?
1801 _ => return Ok(None),
1804 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1805 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1808 fn is_named_param(&self) -> bool {
1809 let offset = match self.token.kind {
1810 token::Interpolated(ref nt) => match **nt {
1811 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1814 token::BinOp(token::And) | token::AndAnd => 1,
1815 _ if self.token.is_keyword(kw::Mut) => 1,
1819 self.look_ahead(offset, |t| t.is_ident())
1820 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1823 fn recover_first_param(&mut self) -> &'static str {
1825 .parse_outer_attributes()
1826 .and_then(|_| self.parse_self_param())
1827 .map_err(|mut e| e.cancel())
1829 Ok(Some(_)) => "method",