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, Unsafe::No)?;
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 unsafety = self.parse_unsafety();
40 self.expect_keyword(kw::Mod)?;
41 let id = self.parse_ident()?;
42 let (module, mut inner_attrs) = if self.eat(&token::Semi) {
43 (Mod { inner: Span::default(), unsafety, items: Vec::new(), inline: false }, Vec::new())
45 self.expect(&token::OpenDelim(token::Brace))?;
46 self.parse_mod(&token::CloseDelim(token::Brace), unsafety)?
48 attrs.append(&mut inner_attrs);
49 Ok((id, ItemKind::Mod(module)))
52 /// Parses the contents of a module (inner attributes followed by module items).
57 ) -> PResult<'a, (Mod, Vec<Attribute>)> {
58 let lo = self.token.span;
59 let attrs = self.parse_inner_attributes()?;
60 let module = self.parse_mod_items(term, lo, unsafety)?;
64 /// Given a termination token, parses all of the items in a module.
70 ) -> PResult<'a, Mod> {
71 let mut items = vec![];
72 while let Some(item) = self.parse_item()? {
74 self.maybe_consume_incorrect_semicolon(&items);
78 let token_str = super::token_descr(&self.token);
79 if !self.maybe_consume_incorrect_semicolon(&items) {
80 let msg = &format!("expected item, found {}", token_str);
81 let mut err = self.struct_span_err(self.token.span, msg);
82 err.span_label(self.token.span, "expected item");
87 let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_token.span };
89 Ok(Mod { inner: inner_lo.to(hi), unsafety, items, inline: true })
93 pub(super) type ItemInfo = (Ident, ItemKind);
96 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
97 self.parse_item_(|_| true).map(|i| i.map(P))
100 fn parse_item_(&mut self, req_name: ReqName) -> PResult<'a, Option<Item>> {
101 let attrs = self.parse_outer_attributes()?;
102 self.parse_item_common(attrs, true, false, req_name)
105 pub(super) fn parse_item_common(
107 mut attrs: Vec<Attribute>,
111 ) -> PResult<'a, Option<Item>> {
112 maybe_whole!(self, NtItem, |item| {
114 mem::swap(&mut item.attrs, &mut attrs);
115 item.attrs.extend(attrs);
116 Some(item.into_inner())
119 let mut unclosed_delims = vec![];
120 let has_attrs = !attrs.is_empty();
121 let parse_item = |this: &mut Self| {
122 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
123 unclosed_delims.append(&mut this.unclosed_delims);
127 let (mut item, tokens) = if has_attrs {
128 let (item, tokens) = self.collect_tokens(parse_item)?;
131 (parse_item(self)?, None)
134 self.unclosed_delims.append(&mut unclosed_delims);
136 // Once we've parsed an item and recorded the tokens we got while
137 // parsing we may want to store `tokens` into the item we're about to
138 // return. Note, though, that we specifically didn't capture tokens
139 // related to outer attributes. The `tokens` field here may later be
140 // used with procedural macros to convert this item back into a token
141 // stream, but during expansion we may be removing attributes as we go
144 // If we've got inner attributes then the `tokens` we've got above holds
145 // these inner attributes. If an inner attribute is expanded we won't
146 // actually remove it from the token stream, so we'll just keep yielding
147 // it (bad!). To work around this case for now we just avoid recording
148 // `tokens` if we detect any inner attributes. This should help keep
149 // expansion correct, but we should fix this bug one day!
150 if let Some(tokens) = tokens {
151 if let Some(item) = &mut item {
152 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
153 item.tokens = Some(tokens);
160 fn parse_item_common_(
162 mut attrs: Vec<Attribute>,
166 ) -> PResult<'a, Option<Item>> {
167 let lo = self.token.span;
168 let vis = self.parse_visibility(FollowedByType::No)?;
169 let mut def = self.parse_defaultness();
170 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
171 if let Some((ident, kind)) = kind {
172 self.error_on_unconsumed_default(def, &kind);
173 let span = lo.to(self.prev_token.span);
174 let id = DUMMY_NODE_ID;
175 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
176 return Ok(Some(item));
179 // At this point, we have failed to parse an item.
180 self.error_on_unmatched_vis(&vis);
181 self.error_on_unmatched_defaultness(def);
183 self.recover_attrs_no_item(&attrs)?;
188 /// Error in-case a non-inherited visibility was parsed but no item followed.
189 fn error_on_unmatched_vis(&self, vis: &Visibility) {
190 if let VisibilityKind::Inherited = vis.kind {
193 let vs = pprust::vis_to_string(&vis);
194 let vs = vs.trim_end();
195 self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs))
196 .span_label(vis.span, "the visibility")
197 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
201 /// Error in-case a `default` was parsed but no item followed.
202 fn error_on_unmatched_defaultness(&self, def: Defaultness) {
203 if let Defaultness::Default(sp) = def {
204 self.struct_span_err(sp, "`default` is not followed by an item")
205 .span_label(sp, "the `default` qualifier")
206 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
211 /// Error in-case `default` was parsed in an in-appropriate context.
212 fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) {
213 if let Defaultness::Default(span) = def {
214 let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr());
215 self.struct_span_err(span, &msg)
216 .span_label(span, "`default` because of this")
217 .note("only associated `fn`, `const`, and `type` items can be `default`")
222 /// Parses one of the items allowed by the flags.
225 attrs: &mut Vec<Attribute>,
226 macros_allowed: bool,
229 def: &mut Defaultness,
231 ) -> PResult<'a, Option<ItemInfo>> {
232 let mut def = || mem::replace(def, Defaultness::Final);
234 let info = if self.eat_keyword(kw::Use) {
236 let tree = self.parse_use_tree()?;
238 (Ident::invalid(), ItemKind::Use(P(tree)))
239 } else if self.check_fn_front_matter() {
241 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name, lo)?;
242 (ident, ItemKind::Fn(def(), sig, generics, body))
243 } else if self.eat_keyword(kw::Extern) {
244 if self.eat_keyword(kw::Crate) {
246 self.parse_item_extern_crate()?
249 self.parse_item_foreign_mod(attrs, Unsafe::No)?
251 } else if self.is_unsafe_foreign_mod() {
253 let unsafety = self.parse_unsafety();
254 self.expect_keyword(kw::Extern)?;
255 self.parse_item_foreign_mod(attrs, unsafety)?
256 } else if self.is_static_global() {
258 self.bump(); // `static`
259 let m = self.parse_mutability();
260 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
261 (ident, ItemKind::Static(ty, m, expr))
262 } else if let Const::Yes(const_span) = self.parse_constness() {
264 self.recover_const_mut(const_span);
265 let (ident, ty, expr) = self.parse_item_global(None)?;
266 (ident, ItemKind::Const(def(), ty, expr))
267 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
269 self.parse_item_trait(attrs, lo)?
270 } else if self.check_keyword(kw::Impl)
271 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
274 self.parse_item_impl(attrs, def())?
275 } else if self.check_keyword(kw::Mod)
276 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
279 self.parse_item_mod(attrs)?
280 } else if self.eat_keyword(kw::Type) {
282 self.parse_type_alias(def())?
283 } else if self.eat_keyword(kw::Enum) {
285 self.parse_item_enum()?
286 } else if self.eat_keyword(kw::Struct) {
288 self.parse_item_struct()?
289 } else if self.is_kw_followed_by_ident(kw::Union) {
291 self.bump(); // `union`
292 self.parse_item_union()?
293 } else if self.eat_keyword(kw::Macro) {
295 self.parse_item_decl_macro(lo)?
296 } else if self.is_macro_rules_item() {
298 self.parse_item_macro_rules(vis)?
299 } else if vis.kind.is_pub() && self.isnt_macro_invocation() {
300 self.recover_missing_kw_before_item()?;
302 } else if macros_allowed && self.check_path() {
303 // MACRO INVOCATION ITEM
304 (Ident::invalid(), ItemKind::MacCall(self.parse_item_macro(vis)?))
311 /// When parsing a statement, would the start of a path be an item?
312 pub(super) fn is_path_start_item(&mut self) -> bool {
313 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
314 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
315 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
316 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
317 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
320 /// Are we sure this could not possibly be a macro invocation?
321 fn isnt_macro_invocation(&mut self) -> bool {
322 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
325 /// Recover on encountering a struct or method definition where the user
326 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
327 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
328 // Space between `pub` keyword and the identifier
331 // ^^^ `sp` points here
332 let sp = self.prev_token.span.between(self.token.span);
333 let full_sp = self.prev_token.span.to(self.token.span);
334 let ident_sp = self.token.span;
335 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
336 // possible public struct definition where `struct` was forgotten
337 let ident = self.parse_ident().unwrap();
338 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
339 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
340 err.span_suggestion_short(
344 Applicability::MaybeIncorrect, // speculative
347 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
348 let ident = self.parse_ident().unwrap();
350 let kw_name = self.recover_first_param();
351 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
352 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
353 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
355 ("fn", kw_name, false)
356 } else if self.check(&token::OpenDelim(token::Brace)) {
358 ("fn", kw_name, false)
359 } else if self.check(&token::Colon) {
363 ("fn` or `struct", "function or struct", true)
366 let msg = format!("missing `{}` for {} definition", kw, kw_name);
367 let mut err = self.struct_span_err(sp, &msg);
369 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
371 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
372 err.span_suggestion_short(
376 Applicability::MachineApplicable,
379 if let Ok(snippet) = self.span_to_snippet(ident_sp) {
382 "if you meant to call a macro, try",
383 format!("{}!", snippet),
384 // this is the `ambiguous` conditional branch
385 Applicability::MaybeIncorrect,
389 "if you meant to call a macro, remove the `pub` \
390 and add a trailing `!` after the identifier",
395 } else if self.look_ahead(1, |t| *t == token::Lt) {
396 let ident = self.parse_ident().unwrap();
397 self.eat_to_tokens(&[&token::Gt]);
399 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
400 ("fn", self.recover_first_param(), false)
401 } else if self.check(&token::OpenDelim(token::Brace)) {
402 ("struct", "struct", false)
404 ("fn` or `struct", "function or struct", true)
406 let msg = format!("missing `{}` for {} definition", kw, kw_name);
407 let mut err = self.struct_span_err(sp, &msg);
409 err.span_suggestion_short(
411 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
413 Applicability::MachineApplicable,
422 /// Parses an item macro, e.g., `item!();`.
423 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
424 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
425 self.expect(&token::Not)?; // `!`
426 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
427 self.eat_semi_for_macro_if_needed(&args);
428 self.complain_if_pub_macro(vis, false);
429 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
432 /// Recover if we parsed attributes and expected an item but there was none.
433 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
434 let (start, end) = match attrs {
436 [x0 @ xn] | [x0, .., xn] => (x0, xn),
438 let msg = if end.is_doc_comment() {
439 "expected item after doc comment"
441 "expected item after attributes"
443 let mut err = self.struct_span_err(end.span, msg);
444 if end.is_doc_comment() {
445 err.span_label(end.span, "this doc comment doesn't document anything");
447 if let [.., penultimate, _] = attrs {
448 err.span_label(start.span.to(penultimate.span), "other attributes here");
453 fn is_async_fn(&self) -> bool {
454 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
457 fn parse_polarity(&mut self) -> ast::ImplPolarity {
458 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
459 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
461 ast::ImplPolarity::Negative(self.prev_token.span)
463 ast::ImplPolarity::Positive
467 /// Parses an implementation item.
470 /// impl<'a, T> TYPE { /* impl items */ }
471 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
472 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
473 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
476 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
478 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
479 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
483 attrs: &mut Vec<Attribute>,
484 defaultness: Defaultness,
485 ) -> PResult<'a, ItemInfo> {
486 let unsafety = self.parse_unsafety();
487 self.expect_keyword(kw::Impl)?;
489 // First, parse generic parameters if necessary.
490 let mut generics = if self.choose_generics_over_qpath(0) {
491 self.parse_generics()?
493 let mut generics = Generics::default();
495 // /\ this is where `generics.span` should point when there are no type params.
496 generics.span = self.prev_token.span.shrink_to_hi();
500 let constness = self.parse_constness();
501 if let Const::Yes(span) = constness {
502 self.sess.gated_spans.gate(sym::const_trait_impl, span);
505 let polarity = self.parse_polarity();
507 // Parse both types and traits as a type, then reinterpret if necessary.
508 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
509 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
511 let span = self.prev_token.span.between(self.token.span);
512 self.struct_span_err(span, "missing trait in a trait impl").emit();
514 kind: TyKind::Path(None, err_path(span)),
523 // If `for` is missing we try to recover.
524 let has_for = self.eat_keyword(kw::For);
525 let missing_for_span = self.prev_token.span.between(self.token.span);
527 let ty_second = if self.token == token::DotDot {
528 // We need to report this error after `cfg` expansion for compatibility reasons
529 self.bump(); // `..`, do not add it to expected tokens
530 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
531 } else if has_for || self.token.can_begin_type() {
532 Some(self.parse_ty()?)
537 generics.where_clause = self.parse_where_clause()?;
539 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
541 let item_kind = match ty_second {
543 // impl Trait for Type
545 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
546 .span_suggestion_short(
550 Applicability::MachineApplicable,
555 let ty_first = ty_first.into_inner();
556 let path = match ty_first.kind {
557 // This notably includes paths passed through `ty` macro fragments (#46438).
558 TyKind::Path(None, path) => path,
560 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
561 err_path(ty_first.span)
564 let trait_ref = TraitRef { path, ref_id: ty_first.id };
572 of_trait: Some(trait_ref),
592 Ok((Ident::invalid(), item_kind))
595 fn parse_item_list<T>(
597 attrs: &mut Vec<Attribute>,
598 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
599 ) -> PResult<'a, Vec<T>> {
600 let open_brace_span = self.token.span;
601 self.expect(&token::OpenDelim(token::Brace))?;
602 attrs.append(&mut self.parse_inner_attributes()?);
604 let mut items = Vec::new();
605 while !self.eat(&token::CloseDelim(token::Brace)) {
606 if self.recover_doc_comment_before_brace() {
609 match parse_item(self) {
611 // We have to bail or we'll potentially never make progress.
612 let non_item_span = self.token.span;
613 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
614 self.struct_span_err(non_item_span, "non-item in item list")
615 .span_label(open_brace_span, "item list starts here")
616 .span_label(non_item_span, "non-item starts here")
617 .span_label(self.prev_token.span, "item list ends here")
621 Ok(Some(item)) => items.extend(item),
623 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
624 err.span_label(open_brace_span, "while parsing this item list starting here")
625 .span_label(self.prev_token.span, "the item list ends here")
634 /// Recover on a doc comment before `}`.
635 fn recover_doc_comment_before_brace(&mut self) -> bool {
636 if let token::DocComment(..) = self.token.kind {
637 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
642 "found a documentation comment that doesn't document anything",
644 .span_label(self.token.span, "this doc comment doesn't document anything")
646 "doc comments must come before what they document, maybe a \
647 comment was intended with `//`?",
657 /// Parses defaultness (i.e., `default` or nothing).
658 fn parse_defaultness(&mut self) -> Defaultness {
659 // We are interested in `default` followed by another identifier.
660 // However, we must avoid keywords that occur as binary operators.
661 // Currently, the only applicable keyword is `as` (`default as Ty`).
662 if self.check_keyword(kw::Default)
663 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
665 self.bump(); // `default`
666 Defaultness::Default(self.prev_token.uninterpolated_span())
672 /// Is this an `(unsafe auto? | auto) trait` item?
673 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
675 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
677 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
680 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
681 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
682 let unsafety = self.parse_unsafety();
683 // Parse optional `auto` prefix.
684 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
686 self.expect_keyword(kw::Trait)?;
687 let ident = self.parse_ident()?;
688 let mut tps = self.parse_generics()?;
690 // Parse optional colon and supertrait bounds.
691 let had_colon = self.eat(&token::Colon);
692 let span_at_colon = self.prev_token.span;
693 let bounds = if had_colon {
694 self.parse_generic_bounds(Some(self.prev_token.span))?
699 let span_before_eq = self.prev_token.span;
700 if self.eat(&token::Eq) {
701 // It's a trait alias.
703 let span = span_at_colon.to(span_before_eq);
704 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
707 let bounds = self.parse_generic_bounds(None)?;
708 tps.where_clause = self.parse_where_clause()?;
711 let whole_span = lo.to(self.prev_token.span);
712 if is_auto == IsAuto::Yes {
713 let msg = "trait aliases cannot be `auto`";
714 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
716 if let Unsafe::Yes(_) = unsafety {
717 let msg = "trait aliases cannot be `unsafe`";
718 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
721 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
723 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
725 // It's a normal trait.
726 tps.where_clause = self.parse_where_clause()?;
727 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
728 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, items)))
732 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
733 self.parse_assoc_item(|_| true)
736 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
737 self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
740 /// Parses associated items.
741 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
742 Ok(self.parse_item_(req_name)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
743 let kind = match AssocItemKind::try_from(kind) {
745 Err(kind) => match kind {
746 ItemKind::Static(a, _, b) => {
747 self.struct_span_err(span, "associated `static` items are not allowed")
749 AssocItemKind::Const(Defaultness::Final, a, b)
751 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
754 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
758 /// Parses a `type` alias with the following grammar:
760 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
762 /// The `"type"` has already been eaten.
763 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
764 let ident = self.parse_ident()?;
765 let mut generics = self.parse_generics()?;
767 // Parse optional colon and param bounds.
769 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
770 generics.where_clause = self.parse_where_clause()?;
772 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
775 Ok((ident, ItemKind::TyAlias(def, generics, bounds, default)))
778 /// Parses a `UseTree`.
781 /// USE_TREE = [`::`] `*` |
782 /// [`::`] `{` USE_TREE_LIST `}` |
784 /// PATH `::` `{` USE_TREE_LIST `}` |
785 /// PATH [`as` IDENT]
787 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
788 let lo = self.token.span;
790 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
791 let kind = if self.check(&token::OpenDelim(token::Brace))
792 || self.check(&token::BinOp(token::Star))
793 || self.is_import_coupler()
795 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
796 let mod_sep_ctxt = self.token.span.ctxt();
797 if self.eat(&token::ModSep) {
800 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
803 self.parse_use_tree_glob_or_nested()?
805 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
806 prefix = self.parse_path(PathStyle::Mod)?;
808 if self.eat(&token::ModSep) {
809 self.parse_use_tree_glob_or_nested()?
811 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
815 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
818 /// Parses `*` or `{...}`.
819 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
820 Ok(if self.eat(&token::BinOp(token::Star)) {
823 UseTreeKind::Nested(self.parse_use_tree_list()?)
827 /// Parses a `UseTreeKind::Nested(list)`.
830 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
832 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
833 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
837 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
838 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
841 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
842 match self.token.ident() {
843 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
847 _ => self.parse_ident(),
851 /// Parses `extern crate` links.
856 /// extern crate foo;
857 /// extern crate bar as foo;
859 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
860 // Accept `extern crate name-like-this` for better diagnostics
861 let orig_name = self.parse_crate_name_with_dashes()?;
862 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
863 (rename, Some(orig_name.name))
868 Ok((item_name, ItemKind::ExternCrate(orig_name)))
871 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
872 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
873 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
875 let mut ident = if self.token.is_keyword(kw::SelfLower) {
876 self.parse_path_segment_ident()
880 let mut idents = vec![];
881 let mut replacement = vec![];
882 let mut fixed_crate_name = false;
883 // Accept `extern crate name-like-this` for better diagnostics.
884 let dash = token::BinOp(token::BinOpToken::Minus);
885 if self.token == dash {
886 // Do not include `-` as part of the expected tokens list.
887 while self.eat(&dash) {
888 fixed_crate_name = true;
889 replacement.push((self.prev_token.span, "_".to_string()));
890 idents.push(self.parse_ident()?);
893 if fixed_crate_name {
894 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
895 let mut fixed_name = format!("{}", ident.name);
897 fixed_name.push_str(&format!("_{}", part.name));
899 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
901 self.struct_span_err(fixed_name_sp, error_msg)
902 .span_label(fixed_name_sp, "dash-separated idents are not valid")
903 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
909 /// Parses `extern` for foreign ABIs modules.
911 /// `extern` is expected to have been consumed before calling this method.
915 /// ```ignore (only-for-syntax-highlight)
919 fn parse_item_foreign_mod(
921 attrs: &mut Vec<Attribute>,
923 ) -> PResult<'a, ItemInfo> {
924 let abi = self.parse_abi(); // ABI?
925 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
926 let module = ast::ForeignMod { unsafety, abi, items };
927 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
930 /// Parses a foreign item (one in an `extern { ... }` block).
931 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
932 Ok(self.parse_item_(|_| true)?.map(|Item { attrs, id, span, vis, ident, kind, tokens }| {
933 let kind = match ForeignItemKind::try_from(kind) {
935 Err(kind) => match kind {
936 ItemKind::Const(_, a, b) => {
937 self.error_on_foreign_const(span, ident);
938 ForeignItemKind::Static(a, Mutability::Not, b)
940 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
943 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
947 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
948 let span = self.sess.source_map().guess_head_span(span);
949 let descr = kind.descr();
950 self.struct_span_err(span, &format!("{} is not supported in {}", descr, ctx))
951 .help(&format!("consider moving the {} out to a nearby module scope", descr))
956 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
957 self.struct_span_err(ident.span, "extern items cannot be `const`")
959 span.with_hi(ident.span.lo()),
960 "try using a static value",
961 "static ".to_string(),
962 Applicability::MachineApplicable,
964 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
968 fn is_unsafe_foreign_mod(&self) -> bool {
969 self.token.is_keyword(kw::Unsafe)
970 && self.is_keyword_ahead(1, &[kw::Extern])
972 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
973 |t| t.kind == token::OpenDelim(token::Brace),
977 fn is_static_global(&mut self) -> bool {
978 if self.check_keyword(kw::Static) {
979 // Check if this could be a closure.
980 !self.look_ahead(1, |token| {
981 if token.is_keyword(kw::Move) {
985 token::BinOp(token::Or) | token::OrOr => true,
994 /// Recover on `const mut` with `const` already eaten.
995 fn recover_const_mut(&mut self, const_span: Span) {
996 if self.eat_keyword(kw::Mut) {
997 let span = self.prev_token.span;
998 self.struct_span_err(span, "const globals cannot be mutable")
999 .span_label(span, "cannot be mutable")
1002 "you might want to declare a static instead",
1003 "static".to_owned(),
1004 Applicability::MaybeIncorrect,
1010 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1011 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1013 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1014 fn parse_item_global(
1016 m: Option<Mutability>,
1017 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1018 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1020 // Parse the type of a `const` or `static mut?` item.
1021 // That is, the `":" $ty` fragment.
1022 let ty = if self.eat(&token::Colon) {
1025 self.recover_missing_const_type(id, m)
1028 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1029 self.expect_semi()?;
1033 /// We were supposed to parse `:` but the `:` was missing.
1034 /// This means that the type is missing.
1035 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1036 // Construct the error and stash it away with the hope
1037 // that typeck will later enrich the error with a type.
1038 let kind = match m {
1039 Some(Mutability::Mut) => "static mut",
1040 Some(Mutability::Not) => "static",
1043 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1044 err.span_suggestion(
1046 "provide a type for the item",
1047 format!("{}: <type>", id),
1048 Applicability::HasPlaceholders,
1050 err.stash(id.span, StashKey::ItemNoType);
1052 // The user intended that the type be inferred,
1053 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1054 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None })
1057 /// Parses an enum declaration.
1058 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1059 let id = self.parse_ident()?;
1060 let mut generics = self.parse_generics()?;
1061 generics.where_clause = self.parse_where_clause()?;
1064 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1065 self.recover_stmt();
1069 let enum_definition =
1070 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1071 Ok((id, ItemKind::Enum(enum_definition, generics)))
1074 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1075 let variant_attrs = self.parse_outer_attributes()?;
1076 let vlo = self.token.span;
1078 let vis = self.parse_visibility(FollowedByType::No)?;
1079 if !self.recover_nested_adt_item(kw::Enum)? {
1082 let ident = self.parse_ident()?;
1084 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1085 // Parse a struct variant.
1086 let (fields, recovered) = self.parse_record_struct_body()?;
1087 VariantData::Struct(fields, recovered)
1088 } else if self.check(&token::OpenDelim(token::Paren)) {
1089 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1091 VariantData::Unit(DUMMY_NODE_ID)
1095 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1097 let vr = ast::Variant {
1101 attrs: variant_attrs,
1104 span: vlo.to(self.prev_token.span),
1105 is_placeholder: false,
1111 /// Parses `struct Foo { ... }`.
1112 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1113 let class_name = self.parse_ident()?;
1115 let mut generics = self.parse_generics()?;
1117 // There is a special case worth noting here, as reported in issue #17904.
1118 // If we are parsing a tuple struct it is the case that the where clause
1119 // should follow the field list. Like so:
1121 // struct Foo<T>(T) where T: Copy;
1123 // If we are parsing a normal record-style struct it is the case
1124 // that the where clause comes before the body, and after the generics.
1125 // So if we look ahead and see a brace or a where-clause we begin
1126 // parsing a record style struct.
1128 // Otherwise if we look ahead and see a paren we parse a tuple-style
1131 let vdata = if self.token.is_keyword(kw::Where) {
1132 generics.where_clause = self.parse_where_clause()?;
1133 if self.eat(&token::Semi) {
1134 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1135 VariantData::Unit(DUMMY_NODE_ID)
1137 // If we see: `struct Foo<T> where T: Copy { ... }`
1138 let (fields, recovered) = self.parse_record_struct_body()?;
1139 VariantData::Struct(fields, recovered)
1141 // No `where` so: `struct Foo<T>;`
1142 } else if self.eat(&token::Semi) {
1143 VariantData::Unit(DUMMY_NODE_ID)
1144 // Record-style struct definition
1145 } else if self.token == token::OpenDelim(token::Brace) {
1146 let (fields, recovered) = self.parse_record_struct_body()?;
1147 VariantData::Struct(fields, recovered)
1148 // Tuple-style struct definition with optional where-clause.
1149 } else if self.token == token::OpenDelim(token::Paren) {
1150 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1151 generics.where_clause = self.parse_where_clause()?;
1152 self.expect_semi()?;
1155 let token_str = super::token_descr(&self.token);
1157 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1160 let mut err = self.struct_span_err(self.token.span, msg);
1161 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1165 Ok((class_name, ItemKind::Struct(vdata, generics)))
1168 /// Parses `union Foo { ... }`.
1169 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1170 let class_name = self.parse_ident()?;
1172 let mut generics = self.parse_generics()?;
1174 let vdata = if self.token.is_keyword(kw::Where) {
1175 generics.where_clause = self.parse_where_clause()?;
1176 let (fields, recovered) = self.parse_record_struct_body()?;
1177 VariantData::Struct(fields, recovered)
1178 } else if self.token == token::OpenDelim(token::Brace) {
1179 let (fields, recovered) = self.parse_record_struct_body()?;
1180 VariantData::Struct(fields, recovered)
1182 let token_str = super::token_descr(&self.token);
1183 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1184 let mut err = self.struct_span_err(self.token.span, msg);
1185 err.span_label(self.token.span, "expected `where` or `{` after union name");
1189 Ok((class_name, ItemKind::Union(vdata, generics)))
1192 fn parse_record_struct_body(
1194 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1195 let mut fields = Vec::new();
1196 let mut recovered = false;
1197 if self.eat(&token::OpenDelim(token::Brace)) {
1198 while self.token != token::CloseDelim(token::Brace) {
1199 let field = self.parse_struct_decl_field().map_err(|e| {
1200 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1205 Ok(field) => fields.push(field),
1212 self.eat(&token::CloseDelim(token::Brace));
1214 let token_str = super::token_descr(&self.token);
1215 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1216 let mut err = self.struct_span_err(self.token.span, msg);
1217 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1221 Ok((fields, recovered))
1224 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1225 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1226 // Unit like structs are handled in parse_item_struct function
1227 self.parse_paren_comma_seq(|p| {
1228 let attrs = p.parse_outer_attributes()?;
1229 let lo = p.token.span;
1230 let vis = p.parse_visibility(FollowedByType::Yes)?;
1231 let ty = p.parse_ty()?;
1233 span: lo.to(ty.span),
1239 is_placeholder: false,
1245 /// Parses an element of a struct declaration.
1246 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1247 let attrs = self.parse_outer_attributes()?;
1248 let lo = self.token.span;
1249 let vis = self.parse_visibility(FollowedByType::No)?;
1250 self.parse_single_struct_field(lo, vis, attrs)
1253 /// Parses a structure field declaration.
1254 fn parse_single_struct_field(
1258 attrs: Vec<Attribute>,
1259 ) -> PResult<'a, StructField> {
1260 let mut seen_comma: bool = false;
1261 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1262 if self.token == token::Comma {
1265 match self.token.kind {
1269 token::CloseDelim(token::Brace) => {}
1270 token::DocComment(..) => {
1271 let previous_span = self.prev_token.span;
1272 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1273 self.bump(); // consume the doc comment
1274 let comma_after_doc_seen = self.eat(&token::Comma);
1275 // `seen_comma` is always false, because we are inside doc block
1276 // condition is here to make code more readable
1277 if !seen_comma && comma_after_doc_seen {
1280 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1284 let sp = self.sess.source_map().next_point(previous_span);
1285 err.span_suggestion(
1287 "missing comma here",
1289 Applicability::MachineApplicable,
1296 let sp = self.prev_token.span.shrink_to_hi();
1297 let mut err = self.struct_span_err(
1299 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1302 // Try to recover extra trailing angle brackets
1303 let mut recovered = false;
1304 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1305 if let Some(last_segment) = segments.last() {
1306 recovered = self.check_trailing_angle_brackets(
1308 &[&token::Comma, &token::CloseDelim(token::Brace)],
1311 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1313 self.eat(&token::Comma);
1314 // `check_trailing_angle_brackets` already emitted a nicer error
1320 if self.token.is_ident() {
1321 // This is likely another field; emit the diagnostic and keep going
1322 err.span_suggestion(
1324 "try adding a comma",
1326 Applicability::MachineApplicable,
1333 // Make sure an error was emitted (either by recovering an angle bracket,
1334 // or by finding an identifier as the next token), since we're
1335 // going to continue parsing
1336 assert!(self.sess.span_diagnostic.has_errors());
1345 /// Parses a structure field.
1346 fn parse_name_and_ty(
1350 attrs: Vec<Attribute>,
1351 ) -> PResult<'a, StructField> {
1352 let name = self.parse_ident_common(false)?;
1353 self.expect(&token::Colon)?;
1354 let ty = self.parse_ty()?;
1356 span: lo.to(self.prev_token.span),
1362 is_placeholder: false,
1366 /// Parses a declarative macro 2.0 definition.
1367 /// The `macro` keyword has already been parsed.
1369 /// MacBody = "{" TOKEN_STREAM "}" ;
1370 /// MacParams = "(" TOKEN_STREAM ")" ;
1371 /// DeclMac = "macro" Ident MacParams? MacBody ;
1373 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1374 let ident = self.parse_ident()?;
1375 let body = if self.check(&token::OpenDelim(token::Brace)) {
1376 self.parse_mac_args()? // `MacBody`
1377 } else if self.check(&token::OpenDelim(token::Paren)) {
1378 let params = self.parse_token_tree(); // `MacParams`
1379 let pspan = params.span();
1380 if !self.check(&token::OpenDelim(token::Brace)) {
1381 return self.unexpected();
1383 let body = self.parse_token_tree(); // `MacBody`
1384 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1385 let bspan = body.span();
1386 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1387 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1388 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1389 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1391 return self.unexpected();
1394 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1395 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1398 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1399 fn is_macro_rules_item(&mut self) -> bool {
1400 self.check_keyword(kw::MacroRules)
1401 && self.look_ahead(1, |t| *t == token::Not)
1402 && self.look_ahead(2, |t| t.is_ident())
1405 /// Parses a `macro_rules! foo { ... }` declarative macro.
1406 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1407 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1408 self.expect(&token::Not)?; // `!`
1410 let ident = self.parse_ident()?;
1411 let body = self.parse_mac_args()?;
1412 self.eat_semi_for_macro_if_needed(&body);
1413 self.complain_if_pub_macro(vis, true);
1415 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1418 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1419 /// If that's not the case, emit an error.
1420 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1421 if let VisibilityKind::Inherited = vis.kind {
1425 let vstr = pprust::vis_to_string(vis);
1426 let vstr = vstr.trim_end();
1428 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1429 self.struct_span_err(vis.span, &msg)
1432 "try exporting the macro",
1433 "#[macro_export]".to_owned(),
1434 Applicability::MaybeIncorrect, // speculative
1438 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1441 "remove the visibility",
1443 Applicability::MachineApplicable,
1445 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1450 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1451 if args.need_semicolon() && !self.eat(&token::Semi) {
1452 self.report_invalid_macro_expansion_item(args);
1456 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1457 let span = args.span().expect("undelimited macro call");
1458 let mut err = self.struct_span_err(
1460 "macros that expand to items must be delimited with braces or followed by a semicolon",
1462 if self.unclosed_delims.is_empty() {
1463 let DelimSpan { open, close } = match args {
1464 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1465 MacArgs::Delimited(dspan, ..) => *dspan,
1467 err.multipart_suggestion(
1468 "change the delimiters to curly braces",
1469 vec![(open, "{".to_string()), (close, '}'.to_string())],
1470 Applicability::MaybeIncorrect,
1473 err.span_suggestion(
1475 "change the delimiters to curly braces",
1476 " { /* items */ }".to_string(),
1477 Applicability::HasPlaceholders,
1480 err.span_suggestion(
1481 span.shrink_to_hi(),
1484 Applicability::MaybeIncorrect,
1489 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1490 /// it is, we try to parse the item and report error about nested types.
1491 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1492 if (self.token.is_keyword(kw::Enum)
1493 || self.token.is_keyword(kw::Struct)
1494 || self.token.is_keyword(kw::Union))
1495 && self.look_ahead(1, |t| t.is_ident())
1497 let kw_token = self.token.clone();
1498 let kw_str = pprust::token_to_string(&kw_token);
1499 let item = self.parse_item()?;
1501 self.struct_span_err(
1503 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1507 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1509 Applicability::MaybeIncorrect,
1512 // We successfully parsed the item but we must inform the caller about nested problem.
1519 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1521 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1522 type ReqName = fn(Edition) -> bool;
1524 /// Parsing of functions and methods.
1525 impl<'a> Parser<'a> {
1526 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1529 attrs: &mut Vec<Attribute>,
1532 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1533 let header = self.parse_fn_front_matter()?; // `const ... fn`
1534 let ident = self.parse_ident()?; // `foo`
1535 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1536 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes)?; // `(p: u8, ...)`
1537 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1539 let mut sig_hi = self.prev_token.span;
1540 let body = self.parse_fn_body(attrs, &mut sig_hi)?; // `;` or `{ ... }`.
1541 let fn_sig_span = sig_lo.to(sig_hi);
1542 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1545 /// Parse the "body" of a function.
1546 /// This can either be `;` when there's no body,
1547 /// or e.g. a block when the function is a provided one.
1550 attrs: &mut Vec<Attribute>,
1552 ) -> PResult<'a, Option<P<Block>>> {
1553 let (inner_attrs, body) = if self.check(&token::Semi) {
1554 // Include the trailing semicolon in the span of the signature
1555 *sig_hi = self.token.span;
1558 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1559 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1560 } else if self.token.kind == token::Eq {
1561 // Recover `fn foo() = $expr;`.
1563 let eq_sp = self.prev_token.span;
1564 let _ = self.parse_expr()?;
1565 self.expect_semi()?; // `;`
1566 let span = eq_sp.to(self.prev_token.span);
1567 self.struct_span_err(span, "function body cannot be `= expression;`")
1568 .multipart_suggestion(
1569 "surround the expression with `{` and `}` instead of `=` and `;`",
1570 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1571 Applicability::MachineApplicable,
1574 (Vec::new(), Some(self.mk_block_err(span)))
1576 return self.expected_semi_or_open_brace();
1578 attrs.extend(inner_attrs);
1582 /// Is the current token the start of an `FnHeader` / not a valid parse?
1583 pub(super) fn check_fn_front_matter(&mut self) -> bool {
1584 // We use an over-approximation here.
1585 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1586 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1587 self.check_keyword(kw::Fn) // Definitely an `fn`.
1588 // `$qual fn` or `$qual $qual`:
1589 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1590 && self.look_ahead(1, |t| {
1591 // `$qual fn`, e.g. `const fn` or `async fn`.
1592 t.is_keyword(kw::Fn)
1593 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1594 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name)
1595 // Rule out 2015 `const async: T = val`.
1597 // Rule out unsafe extern block.
1598 && !self.is_unsafe_foreign_mod())
1601 || self.check_keyword(kw::Extern)
1602 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1603 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1606 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1607 /// up to and including the `fn` keyword. The formal grammar is:
1610 /// Extern = "extern" StringLit? ;
1611 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1612 /// FnFrontMatter = FnQual "fn" ;
1614 pub(super) fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1615 let constness = self.parse_constness();
1616 let asyncness = self.parse_asyncness();
1617 let unsafety = self.parse_unsafety();
1618 let ext = self.parse_extern()?;
1620 if let Async::Yes { span, .. } = asyncness {
1621 self.ban_async_in_2015(span);
1624 if !self.eat_keyword(kw::Fn) {
1625 // It is possible for `expect_one_of` to recover given the contents of
1626 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1627 // account for this.
1628 if !self.expect_one_of(&[], &[])? {
1633 Ok(FnHeader { constness, unsafety, asyncness, ext })
1636 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1637 fn ban_async_in_2015(&self, span: Span) {
1638 if span.rust_2015() {
1639 let diag = self.diagnostic();
1640 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in the 2015 edition")
1641 .span_label(span, "to use `async fn`, switch to Rust 2018")
1642 .help("set `edition = \"2018\"` in `Cargo.toml`")
1643 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1648 /// Parses the parameter list and result type of a function declaration.
1649 pub(super) fn parse_fn_decl(
1652 ret_allow_plus: AllowPlus,
1653 ) -> PResult<'a, P<FnDecl>> {
1655 inputs: self.parse_fn_params(req_name)?,
1656 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?,
1660 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1661 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1662 let mut first_param = true;
1663 // Parse the arguments, starting out with `self` being allowed...
1664 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1665 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1667 let lo = p.prev_token.span;
1668 // Skip every token until next possible arg or end.
1669 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1670 // Create a placeholder argument for proper arg count (issue #34264).
1671 Ok(dummy_arg(Ident::new(kw::Invalid, lo.to(p.prev_token.span))))
1673 // ...now that we've parsed the first argument, `self` is no longer allowed.
1674 first_param = false;
1677 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1678 self.deduplicate_recovered_params_names(&mut params);
1682 /// Parses a single function parameter.
1684 /// - `self` is syntactically allowed when `first_param` holds.
1685 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1686 let lo = self.token.span;
1687 let attrs = self.parse_outer_attributes()?;
1689 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1690 if let Some(mut param) = self.parse_self_param()? {
1691 param.attrs = attrs.into();
1692 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1695 let is_name_required = match self.token.kind {
1696 token::DotDotDot => false,
1697 _ => req_name(self.token.span.edition()),
1699 let (pat, ty) = if is_name_required || self.is_named_param() {
1700 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1702 let pat = self.parse_fn_param_pat()?;
1703 if let Err(mut err) = self.expect(&token::Colon) {
1704 return if let Some(ident) =
1705 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1708 Ok(dummy_arg(ident))
1714 self.eat_incorrect_doc_comment_for_param_type();
1715 (pat, self.parse_ty_for_param()?)
1717 debug!("parse_param_general ident_to_pat");
1718 let parser_snapshot_before_ty = self.clone();
1719 self.eat_incorrect_doc_comment_for_param_type();
1720 let mut ty = self.parse_ty_for_param();
1722 && self.token != token::Comma
1723 && self.token != token::CloseDelim(token::Paren)
1725 // This wasn't actually a type, but a pattern looking like a type,
1726 // so we are going to rollback and re-parse for recovery.
1727 ty = self.unexpected();
1731 let ident = Ident::new(kw::Invalid, self.prev_token.span);
1732 let bm = BindingMode::ByValue(Mutability::Not);
1733 let pat = self.mk_pat_ident(ty.span, bm, ident);
1736 // If this is a C-variadic argument and we hit an error, return the error.
1737 Err(err) if self.token == token::DotDotDot => return Err(err),
1738 // Recover from attempting to parse the argument as a type without pattern.
1741 *self = parser_snapshot_before_ty;
1742 self.recover_arg_parse()?
1747 let span = lo.until(self.token.span);
1750 attrs: attrs.into(),
1751 id: ast::DUMMY_NODE_ID,
1752 is_placeholder: false,
1759 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1760 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1761 // Extract an identifier *after* having confirmed that the token is one.
1762 let expect_self_ident = |this: &mut Self| match this.token.ident() {
1763 Some((ident, false)) => {
1767 _ => unreachable!(),
1769 // Is `self` `n` tokens ahead?
1770 let is_isolated_self = |this: &Self, n| {
1771 this.is_keyword_ahead(n, &[kw::SelfLower])
1772 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1774 // Is `mut self` `n` tokens ahead?
1775 let is_isolated_mut_self =
1776 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1777 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1778 let parse_self_possibly_typed = |this: &mut Self, m| {
1779 let eself_ident = expect_self_ident(this);
1780 let eself_hi = this.prev_token.span;
1781 let eself = if this.eat(&token::Colon) {
1782 SelfKind::Explicit(this.parse_ty()?, m)
1786 Ok((eself, eself_ident, eself_hi))
1788 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1789 let recover_self_ptr = |this: &mut Self| {
1790 let msg = "cannot pass `self` by raw pointer";
1791 let span = this.token.span;
1792 this.struct_span_err(span, msg).span_label(span, msg).emit();
1794 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
1797 // Parse optional `self` parameter of a method.
1798 // Only a limited set of initial token sequences is considered `self` parameters; anything
1799 // else is parsed as a normal function parameter list, so some lookahead is required.
1800 let eself_lo = self.token.span;
1801 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
1802 token::BinOp(token::And) => {
1803 let eself = if is_isolated_self(self, 1) {
1806 SelfKind::Region(None, Mutability::Not)
1807 } else if is_isolated_mut_self(self, 1) {
1811 SelfKind::Region(None, Mutability::Mut)
1812 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1815 let lt = self.expect_lifetime();
1816 SelfKind::Region(Some(lt), Mutability::Not)
1817 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1820 let lt = self.expect_lifetime();
1822 SelfKind::Region(Some(lt), Mutability::Mut)
1827 (eself, expect_self_ident(self), self.prev_token.span)
1830 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1832 recover_self_ptr(self)?
1834 // `*mut self` and `*const self`
1835 token::BinOp(token::Star)
1836 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1840 recover_self_ptr(self)?
1842 // `self` and `self: TYPE`
1843 token::Ident(..) if is_isolated_self(self, 0) => {
1844 parse_self_possibly_typed(self, Mutability::Not)?
1846 // `mut self` and `mut self: TYPE`
1847 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1849 parse_self_possibly_typed(self, Mutability::Mut)?
1851 _ => return Ok(None),
1854 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1855 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1858 fn is_named_param(&self) -> bool {
1859 let offset = match self.token.kind {
1860 token::Interpolated(ref nt) => match **nt {
1861 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1864 token::BinOp(token::And) | token::AndAnd => 1,
1865 _ if self.token.is_keyword(kw::Mut) => 1,
1869 self.look_ahead(offset, |t| t.is_ident())
1870 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1873 fn recover_first_param(&mut self) -> &'static str {
1875 .parse_outer_attributes()
1876 .and_then(|_| self.parse_self_param())
1877 .map_err(|mut e| e.cancel())
1879 Ok(Some(_)) => "method",