1 use super::diagnostics
::{dummy_arg, ConsumeClosingDelim, Error}
;
2 use super::ty
::{AllowPlus, RecoverQPath, RecoverReturnSign}
;
3 use super::{FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken}
;
5 use crate::{maybe_collect_tokens, maybe_whole}
;
9 use rustc_ast
::token
::{self, TokenKind}
;
10 use rustc_ast
::tokenstream
::{DelimSpan, TokenStream, TokenTree}
;
11 use rustc_ast
::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID}
;
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, LATEST_STABLE_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(ForceCollect
::No
)?
{
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, force_collect
: ForceCollect
) -> PResult
<'a
, Option
<P
<Item
>>> {
97 self.parse_item_(|_
| true, force_collect
).map(|i
| i
.map(P
))
103 force_collect
: ForceCollect
,
104 ) -> PResult
<'a
, Option
<Item
>> {
105 let attrs
= self.parse_outer_attributes()?
;
106 self.parse_item_common(attrs
, true, false, req_name
, force_collect
)
109 pub(super) fn parse_item_common(
111 mut attrs
: Vec
<Attribute
>,
115 force_collect
: ForceCollect
,
116 ) -> PResult
<'a
, Option
<Item
>> {
117 maybe_whole
!(self, NtItem
, |item
| {
119 mem
::swap(&mut item
.attrs
, &mut attrs
);
120 item
.attrs
.extend(attrs
);
121 Some(item
.into_inner())
124 let mut unclosed_delims
= vec
![];
125 let item
= maybe_collect_tokens
!(self, force_collect
, &attrs
, |this
: &mut Self| {
126 let item
= this
.parse_item_common_(attrs
, mac_allowed
, attrs_allowed
, req_name
);
127 unclosed_delims
.append(&mut this
.unclosed_delims
);
128 Ok((item?
, TrailingToken
::None
))
131 self.unclosed_delims
.append(&mut unclosed_delims
);
135 fn parse_item_common_(
137 mut attrs
: Vec
<Attribute
>,
141 ) -> PResult
<'a
, Option
<Item
>> {
142 let lo
= self.token
.span
;
143 let vis
= self.parse_visibility(FollowedByType
::No
)?
;
144 let mut def
= self.parse_defaultness();
145 let kind
= self.parse_item_kind(&mut attrs
, mac_allowed
, lo
, &vis
, &mut def
, req_name
)?
;
146 if let Some((ident
, kind
)) = kind
{
147 self.error_on_unconsumed_default(def
, &kind
);
148 let span
= lo
.to(self.prev_token
.span
);
149 let id
= DUMMY_NODE_ID
;
150 let item
= Item { ident, attrs, id, kind, vis, span, tokens: None }
;
151 return Ok(Some(item
));
154 // At this point, we have failed to parse an item.
155 self.error_on_unmatched_vis(&vis
);
156 self.error_on_unmatched_defaultness(def
);
158 self.recover_attrs_no_item(&attrs
)?
;
163 /// Error in-case a non-inherited visibility was parsed but no item followed.
164 fn error_on_unmatched_vis(&self, vis
: &Visibility
) {
165 if let VisibilityKind
::Inherited
= vis
.kind
{
168 let vs
= pprust
::vis_to_string(&vis
);
169 let vs
= vs
.trim_end();
170 self.struct_span_err(vis
.span
, &format
!("visibility `{}` is not followed by an item", vs
))
171 .span_label(vis
.span
, "the visibility")
172 .help(&format
!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs
))
176 /// Error in-case a `default` was parsed but no item followed.
177 fn error_on_unmatched_defaultness(&self, def
: Defaultness
) {
178 if let Defaultness
::Default(sp
) = def
{
179 self.struct_span_err(sp
, "`default` is not followed by an item")
180 .span_label(sp
, "the `default` qualifier")
181 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
186 /// Error in-case `default` was parsed in an in-appropriate context.
187 fn error_on_unconsumed_default(&self, def
: Defaultness
, kind
: &ItemKind
) {
188 if let Defaultness
::Default(span
) = def
{
189 let msg
= format
!("{} {} cannot be `default`", kind
.article(), kind
.descr());
190 self.struct_span_err(span
, &msg
)
191 .span_label(span
, "`default` because of this")
192 .note("only associated `fn`, `const`, and `type` items can be `default`")
197 /// Parses one of the items allowed by the flags.
200 attrs
: &mut Vec
<Attribute
>,
201 macros_allowed
: bool
,
204 def
: &mut Defaultness
,
206 ) -> PResult
<'a
, Option
<ItemInfo
>> {
207 let mut def
= || mem
::replace(def
, Defaultness
::Final
);
209 let info
= if self.eat_keyword(kw
::Use
) {
211 let tree
= self.parse_use_tree()?
;
213 // If wildcard or glob-like brace syntax doesn't have `;`,
214 // the user may not know `*` or `{}` should be the last.
215 if let Err(mut e
) = self.expect_semi() {
217 UseTreeKind
::Glob
=> {
218 e
.note("the wildcard token must be last on the path").emit();
220 UseTreeKind
::Nested(..) => {
221 e
.note("glob-like brace syntax must be last on the path").emit();
228 (Ident
::invalid(), ItemKind
::Use(P(tree
)))
229 } else if self.check_fn_front_matter() {
231 let (ident
, sig
, generics
, body
) = self.parse_fn(attrs
, req_name
, lo
)?
;
232 (ident
, ItemKind
::Fn(box FnKind(def(), sig
, generics
, body
)))
233 } else if self.eat_keyword(kw
::Extern
) {
234 if self.eat_keyword(kw
::Crate
) {
236 self.parse_item_extern_crate()?
239 self.parse_item_foreign_mod(attrs
, Unsafe
::No
)?
241 } else if self.is_unsafe_foreign_mod() {
243 let unsafety
= self.parse_unsafety();
244 self.expect_keyword(kw
::Extern
)?
;
245 self.parse_item_foreign_mod(attrs
, unsafety
)?
246 } else if self.is_static_global() {
248 self.bump(); // `static`
249 let m
= self.parse_mutability();
250 let (ident
, ty
, expr
) = self.parse_item_global(Some(m
))?
;
251 (ident
, ItemKind
::Static(ty
, m
, expr
))
252 } else if let Const
::Yes(const_span
) = self.parse_constness() {
254 if self.token
.is_keyword(kw
::Impl
) {
255 // recover from `const impl`, suggest `impl const`
256 self.recover_const_impl(const_span
, attrs
, def())?
258 self.recover_const_mut(const_span
);
259 let (ident
, ty
, expr
) = self.parse_item_global(None
)?
;
260 (ident
, ItemKind
::Const(def(), ty
, expr
))
262 } else if self.check_keyword(kw
::Trait
) || self.check_auto_or_unsafe_trait_item() {
264 self.parse_item_trait(attrs
, lo
)?
265 } else if self.check_keyword(kw
::Impl
)
266 || self.check_keyword(kw
::Unsafe
) && self.is_keyword_ahead(1, &[kw
::Impl
])
269 self.parse_item_impl(attrs
, def())?
270 } else if self.check_keyword(kw
::Mod
)
271 || self.check_keyword(kw
::Unsafe
) && self.is_keyword_ahead(1, &[kw
::Mod
])
274 self.parse_item_mod(attrs
)?
275 } else if self.eat_keyword(kw
::Type
) {
277 self.parse_type_alias(def())?
278 } else if self.eat_keyword(kw
::Enum
) {
280 self.parse_item_enum()?
281 } else if self.eat_keyword(kw
::Struct
) {
283 self.parse_item_struct()?
284 } else if self.is_kw_followed_by_ident(kw
::Union
) {
286 self.bump(); // `union`
287 self.parse_item_union()?
288 } else if self.eat_keyword(kw
::Macro
) {
290 self.parse_item_decl_macro(lo
)?
291 } else if self.is_macro_rules_item() {
293 self.parse_item_macro_rules(vis
)?
294 } else if vis
.kind
.is_pub() && self.isnt_macro_invocation() {
295 self.recover_missing_kw_before_item()?
;
297 } else if macros_allowed
&& self.check_path() {
298 // MACRO INVOCATION ITEM
299 (Ident
::invalid(), ItemKind
::MacCall(self.parse_item_macro(vis
)?
))
306 /// When parsing a statement, would the start of a path be an item?
307 pub(super) fn is_path_start_item(&mut self) -> bool
{
308 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
309 || self.is_kw_followed_by_ident(kw
::Union
) // no: `union::b`, yes: `union U { .. }`
310 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
311 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
312 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
315 /// Are we sure this could not possibly be a macro invocation?
316 fn isnt_macro_invocation(&mut self) -> bool
{
317 self.check_ident() && self.look_ahead(1, |t
| *t
!= token
::Not
&& *t
!= token
::ModSep
)
320 /// Recover on encountering a struct or method definition where the user
321 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
322 fn recover_missing_kw_before_item(&mut self) -> PResult
<'a
, ()> {
323 // Space between `pub` keyword and the identifier
326 // ^^^ `sp` points here
327 let sp
= self.prev_token
.span
.between(self.token
.span
);
328 let full_sp
= self.prev_token
.span
.to(self.token
.span
);
329 let ident_sp
= self.token
.span
;
330 if self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
)) {
331 // possible public struct definition where `struct` was forgotten
332 let ident
= self.parse_ident().unwrap();
333 let msg
= format
!("add `struct` here to parse `{}` as a public struct", ident
);
334 let mut err
= self.struct_span_err(sp
, "missing `struct` for struct definition");
335 err
.span_suggestion_short(
339 Applicability
::MaybeIncorrect
, // speculative
342 } else if self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Paren
)) {
343 let ident
= self.parse_ident().unwrap();
345 let kw_name
= self.recover_first_param();
346 self.consume_block(token
::Paren
, ConsumeClosingDelim
::Yes
);
347 let (kw
, kw_name
, ambiguous
) = if self.check(&token
::RArrow
) {
348 self.eat_to_tokens(&[&token
::OpenDelim(token
::Brace
)]);
350 ("fn", kw_name
, false)
351 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
353 ("fn", kw_name
, false)
354 } else if self.check(&token
::Colon
) {
358 ("fn` or `struct", "function or struct", true)
361 let msg
= format
!("missing `{}` for {} definition", kw
, kw_name
);
362 let mut err
= self.struct_span_err(sp
, &msg
);
364 self.consume_block(token
::Brace
, ConsumeClosingDelim
::Yes
);
366 format
!("add `{}` here to parse `{}` as a public {}", kw
, ident
, kw_name
);
367 err
.span_suggestion_short(
371 Applicability
::MachineApplicable
,
373 } else if let Ok(snippet
) = self.span_to_snippet(ident_sp
) {
376 "if you meant to call a macro, try",
377 format
!("{}!", snippet
),
378 // this is the `ambiguous` conditional branch
379 Applicability
::MaybeIncorrect
,
383 "if you meant to call a macro, remove the `pub` \
384 and add a trailing `!` after the identifier",
388 } else if self.look_ahead(1, |t
| *t
== token
::Lt
) {
389 let ident
= self.parse_ident().unwrap();
390 self.eat_to_tokens(&[&token
::Gt
]);
392 let (kw
, kw_name
, ambiguous
) = if self.eat(&token
::OpenDelim(token
::Paren
)) {
393 ("fn", self.recover_first_param(), false)
394 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
395 ("struct", "struct", false)
397 ("fn` or `struct", "function or struct", true)
399 let msg
= format
!("missing `{}` for {} definition", kw
, kw_name
);
400 let mut err
= self.struct_span_err(sp
, &msg
);
402 err
.span_suggestion_short(
404 &format
!("add `{}` here to parse `{}` as a public {}", kw
, ident
, kw_name
),
406 Applicability
::MachineApplicable
,
415 /// Parses an item macro, e.g., `item!();`.
416 fn parse_item_macro(&mut self, vis
: &Visibility
) -> PResult
<'a
, MacCall
> {
417 let path
= self.parse_path(PathStyle
::Mod
)?
; // `foo::bar`
418 self.expect(&token
::Not
)?
; // `!`
419 let args
= self.parse_mac_args()?
; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
420 self.eat_semi_for_macro_if_needed(&args
);
421 self.complain_if_pub_macro(vis
, false);
422 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription }
)
425 /// Recover if we parsed attributes and expected an item but there was none.
426 fn recover_attrs_no_item(&mut self, attrs
: &[Attribute
]) -> PResult
<'a
, ()> {
427 let (start
, end
) = match attrs
{
429 [x0 @ xn
] | [x0
, .., xn
] => (x0
, xn
),
431 let msg
= if end
.is_doc_comment() {
432 "expected item after doc comment"
434 "expected item after attributes"
436 let mut err
= self.struct_span_err(end
.span
, msg
);
437 if end
.is_doc_comment() {
438 err
.span_label(end
.span
, "this doc comment doesn't document anything");
440 if let [.., penultimate
, _
] = attrs
{
441 err
.span_label(start
.span
.to(penultimate
.span
), "other attributes here");
446 fn is_async_fn(&self) -> bool
{
447 self.token
.is_keyword(kw
::Async
) && self.is_keyword_ahead(1, &[kw
::Fn
])
450 fn parse_polarity(&mut self) -> ast
::ImplPolarity
{
451 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
452 if self.check(&token
::Not
) && self.look_ahead(1, |t
| t
.can_begin_type()) {
454 ast
::ImplPolarity
::Negative(self.prev_token
.span
)
456 ast
::ImplPolarity
::Positive
460 /// Parses an implementation item.
463 /// impl<'a, T> TYPE { /* impl items */ }
464 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
465 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
466 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
469 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
471 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
472 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
476 attrs
: &mut Vec
<Attribute
>,
477 defaultness
: Defaultness
,
478 ) -> PResult
<'a
, ItemInfo
> {
479 let unsafety
= self.parse_unsafety();
480 self.expect_keyword(kw
::Impl
)?
;
482 // First, parse generic parameters if necessary.
483 let mut generics
= if self.choose_generics_over_qpath(0) {
484 self.parse_generics()?
486 let mut generics
= Generics
::default();
488 // /\ this is where `generics.span` should point when there are no type params.
489 generics
.span
= self.prev_token
.span
.shrink_to_hi();
493 let constness
= self.parse_constness();
494 if let Const
::Yes(span
) = constness
{
495 self.sess
.gated_spans
.gate(sym
::const_trait_impl
, span
);
498 let polarity
= self.parse_polarity();
500 // Parse both types and traits as a type, then reinterpret if necessary.
501 let err_path
= |span
| ast
::Path
::from_ident(Ident
::new(kw
::Empty
, span
));
502 let ty_first
= if self.token
.is_keyword(kw
::For
) && self.look_ahead(1, |t
| t
!= &token
::Lt
)
504 let span
= self.prev_token
.span
.between(self.token
.span
);
505 self.struct_span_err(span
, "missing trait in a trait impl").emit();
507 kind
: TyKind
::Path(None
, err_path(span
)),
516 // If `for` is missing we try to recover.
517 let has_for
= self.eat_keyword(kw
::For
);
518 let missing_for_span
= self.prev_token
.span
.between(self.token
.span
);
520 let ty_second
= if self.token
== token
::DotDot
{
521 // We need to report this error after `cfg` expansion for compatibility reasons
522 self.bump(); // `..`, do not add it to expected tokens
523 Some(self.mk_ty(self.prev_token
.span
, TyKind
::Err
))
524 } else if has_for
|| self.token
.can_begin_type() {
525 Some(self.parse_ty()?
)
530 generics
.where_clause
= self.parse_where_clause()?
;
532 let impl_items
= self.parse_item_list(attrs
, |p
| p
.parse_impl_item())?
;
534 let item_kind
= match ty_second
{
536 // impl Trait for Type
538 self.struct_span_err(missing_for_span
, "missing `for` in a trait impl")
539 .span_suggestion_short(
543 Applicability
::MachineApplicable
,
548 let ty_first
= ty_first
.into_inner();
549 let path
= match ty_first
.kind
{
550 // This notably includes paths passed through `ty` macro fragments (#46438).
551 TyKind
::Path(None
, path
) => path
,
553 self.struct_span_err(ty_first
.span
, "expected a trait, found type").emit();
554 err_path(ty_first
.span
)
557 let trait_ref
= TraitRef { path, ref_id: ty_first.id }
;
559 ItemKind
::Impl(box ImplKind
{
565 of_trait
: Some(trait_ref
),
572 ItemKind
::Impl(box ImplKind
{
585 Ok((Ident
::invalid(), item_kind
))
588 fn parse_item_list
<T
>(
590 attrs
: &mut Vec
<Attribute
>,
591 mut parse_item
: impl FnMut(&mut Parser
<'a
>) -> PResult
<'a
, Option
<Option
<T
>>>,
592 ) -> PResult
<'a
, Vec
<T
>> {
593 let open_brace_span
= self.token
.span
;
594 self.expect(&token
::OpenDelim(token
::Brace
))?
;
595 attrs
.append(&mut self.parse_inner_attributes()?
);
597 let mut items
= Vec
::new();
598 while !self.eat(&token
::CloseDelim(token
::Brace
)) {
599 if self.recover_doc_comment_before_brace() {
602 match parse_item(self) {
604 // We have to bail or we'll potentially never make progress.
605 let non_item_span
= self.token
.span
;
606 self.consume_block(token
::Brace
, ConsumeClosingDelim
::Yes
);
607 self.struct_span_err(non_item_span
, "non-item in item list")
608 .span_label(open_brace_span
, "item list starts here")
609 .span_label(non_item_span
, "non-item starts here")
610 .span_label(self.prev_token
.span
, "item list ends here")
614 Ok(Some(item
)) => items
.extend(item
),
616 self.consume_block(token
::Brace
, ConsumeClosingDelim
::Yes
);
617 err
.span_label(open_brace_span
, "while parsing this item list starting here")
618 .span_label(self.prev_token
.span
, "the item list ends here")
627 /// Recover on a doc comment before `}`.
628 fn recover_doc_comment_before_brace(&mut self) -> bool
{
629 if let token
::DocComment(..) = self.token
.kind
{
630 if self.look_ahead(1, |tok
| tok
== &token
::CloseDelim(token
::Brace
)) {
635 "found a documentation comment that doesn't document anything",
637 .span_label(self.token
.span
, "this doc comment doesn't document anything")
639 "doc comments must come before what they document, maybe a \
640 comment was intended with `//`?",
650 /// Parses defaultness (i.e., `default` or nothing).
651 fn parse_defaultness(&mut self) -> Defaultness
{
652 // We are interested in `default` followed by another identifier.
653 // However, we must avoid keywords that occur as binary operators.
654 // Currently, the only applicable keyword is `as` (`default as Ty`).
655 if self.check_keyword(kw
::Default
)
656 && self.look_ahead(1, |t
| t
.is_non_raw_ident_where(|i
| i
.name
!= kw
::As
))
658 self.bump(); // `default`
659 Defaultness
::Default(self.prev_token
.uninterpolated_span())
665 /// Is this an `(unsafe auto? | auto) trait` item?
666 fn check_auto_or_unsafe_trait_item(&mut self) -> bool
{
668 self.check_keyword(kw
::Auto
) && self.is_keyword_ahead(1, &[kw
::Trait
])
670 || self.check_keyword(kw
::Unsafe
) && self.is_keyword_ahead(1, &[kw
::Trait
, kw
::Auto
])
673 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
674 fn parse_item_trait(&mut self, attrs
: &mut Vec
<Attribute
>, lo
: Span
) -> PResult
<'a
, ItemInfo
> {
675 let unsafety
= self.parse_unsafety();
676 // Parse optional `auto` prefix.
677 let is_auto
= if self.eat_keyword(kw
::Auto
) { IsAuto::Yes }
else { IsAuto::No }
;
679 self.expect_keyword(kw
::Trait
)?
;
680 let ident
= self.parse_ident()?
;
681 let mut tps
= self.parse_generics()?
;
683 // Parse optional colon and supertrait bounds.
684 let had_colon
= self.eat(&token
::Colon
);
685 let span_at_colon
= self.prev_token
.span
;
686 let bounds
= if had_colon
{
687 self.parse_generic_bounds(Some(self.prev_token
.span
))?
692 let span_before_eq
= self.prev_token
.span
;
693 if self.eat(&token
::Eq
) {
694 // It's a trait alias.
696 let span
= span_at_colon
.to(span_before_eq
);
697 self.struct_span_err(span
, "bounds are not allowed on trait aliases").emit();
700 let bounds
= self.parse_generic_bounds(None
)?
;
701 tps
.where_clause
= self.parse_where_clause()?
;
704 let whole_span
= lo
.to(self.prev_token
.span
);
705 if is_auto
== IsAuto
::Yes
{
706 let msg
= "trait aliases cannot be `auto`";
707 self.struct_span_err(whole_span
, msg
).span_label(whole_span
, msg
).emit();
709 if let Unsafe
::Yes(_
) = unsafety
{
710 let msg
= "trait aliases cannot be `unsafe`";
711 self.struct_span_err(whole_span
, msg
).span_label(whole_span
, msg
).emit();
714 self.sess
.gated_spans
.gate(sym
::trait_alias
, whole_span
);
716 Ok((ident
, ItemKind
::TraitAlias(tps
, bounds
)))
718 // It's a normal trait.
719 tps
.where_clause
= self.parse_where_clause()?
;
720 let items
= self.parse_item_list(attrs
, |p
| p
.parse_trait_item())?
;
721 Ok((ident
, ItemKind
::Trait(box TraitKind(is_auto
, unsafety
, tps
, bounds
, items
))))
725 pub fn parse_impl_item(&mut self) -> PResult
<'a
, Option
<Option
<P
<AssocItem
>>>> {
726 self.parse_assoc_item(|_
| true)
729 pub fn parse_trait_item(&mut self) -> PResult
<'a
, Option
<Option
<P
<AssocItem
>>>> {
730 self.parse_assoc_item(|edition
| edition
>= Edition
::Edition2018
)
733 /// Parses associated items.
734 fn parse_assoc_item(&mut self, req_name
: ReqName
) -> PResult
<'a
, Option
<Option
<P
<AssocItem
>>>> {
735 Ok(self.parse_item_(req_name
, ForceCollect
::No
)?
.map(
736 |Item { attrs, id, span, vis, ident, kind, tokens }
| {
737 let kind
= match AssocItemKind
::try_from(kind
) {
739 Err(kind
) => match kind
{
740 ItemKind
::Static(a
, _
, b
) => {
741 self.struct_span_err(span
, "associated `static` items are not allowed")
743 AssocItemKind
::Const(Defaultness
::Final
, a
, b
)
745 _
=> return self.error_bad_item_kind(span
, &kind
, "`trait`s or `impl`s"),
748 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }
))
753 /// Parses a `type` alias with the following grammar:
755 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
757 /// The `"type"` has already been eaten.
758 fn parse_type_alias(&mut self, def
: Defaultness
) -> PResult
<'a
, ItemInfo
> {
759 let ident
= self.parse_ident()?
;
760 let mut generics
= self.parse_generics()?
;
762 // Parse optional colon and param bounds.
764 if self.eat(&token
::Colon
) { self.parse_generic_bounds(None)? }
else { Vec::new() }
;
765 generics
.where_clause
= self.parse_where_clause()?
;
767 let default = if self.eat(&token
::Eq
) { Some(self.parse_ty()?) }
else { None }
;
770 Ok((ident
, ItemKind
::TyAlias(box TyAliasKind(def
, generics
, bounds
, default))))
773 /// Parses a `UseTree`.
776 /// USE_TREE = [`::`] `*` |
777 /// [`::`] `{` USE_TREE_LIST `}` |
779 /// PATH `::` `{` USE_TREE_LIST `}` |
780 /// PATH [`as` IDENT]
782 fn parse_use_tree(&mut self) -> PResult
<'a
, UseTree
> {
783 let lo
= self.token
.span
;
785 let mut prefix
= ast
::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None }
;
786 let kind
= if self.check(&token
::OpenDelim(token
::Brace
))
787 || self.check(&token
::BinOp(token
::Star
))
788 || self.is_import_coupler()
790 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
791 let mod_sep_ctxt
= self.token
.span
.ctxt();
792 if self.eat(&token
::ModSep
) {
795 .push(PathSegment
::path_root(lo
.shrink_to_lo().with_ctxt(mod_sep_ctxt
)));
798 self.parse_use_tree_glob_or_nested()?
800 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
801 prefix
= self.parse_path(PathStyle
::Mod
)?
;
803 if self.eat(&token
::ModSep
) {
804 self.parse_use_tree_glob_or_nested()?
806 UseTreeKind
::Simple(self.parse_rename()?
, DUMMY_NODE_ID
, DUMMY_NODE_ID
)
810 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) }
)
813 /// Parses `*` or `{...}`.
814 fn parse_use_tree_glob_or_nested(&mut self) -> PResult
<'a
, UseTreeKind
> {
815 Ok(if self.eat(&token
::BinOp(token
::Star
)) {
818 UseTreeKind
::Nested(self.parse_use_tree_list()?
)
822 /// Parses a `UseTreeKind::Nested(list)`.
825 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
827 fn parse_use_tree_list(&mut self) -> PResult
<'a
, Vec
<(UseTree
, ast
::NodeId
)>> {
828 self.parse_delim_comma_seq(token
::Brace
, |p
| Ok((p
.parse_use_tree()?
, DUMMY_NODE_ID
)))
832 fn parse_rename(&mut self) -> PResult
<'a
, Option
<Ident
>> {
833 if self.eat_keyword(kw
::As
) { self.parse_ident_or_underscore().map(Some) }
else { Ok(None) }
836 fn parse_ident_or_underscore(&mut self) -> PResult
<'a
, Ident
> {
837 match self.token
.ident() {
838 Some((ident @ Ident { name: kw::Underscore, .. }
, false)) => {
842 _
=> self.parse_ident(),
846 /// Parses `extern crate` links.
851 /// extern crate foo;
852 /// extern crate bar as foo;
854 fn parse_item_extern_crate(&mut self) -> PResult
<'a
, ItemInfo
> {
855 // Accept `extern crate name-like-this` for better diagnostics
856 let orig_name
= self.parse_crate_name_with_dashes()?
;
857 let (item_name
, orig_name
) = if let Some(rename
) = self.parse_rename()?
{
858 (rename
, Some(orig_name
.name
))
863 Ok((item_name
, ItemKind
::ExternCrate(orig_name
)))
866 fn parse_crate_name_with_dashes(&mut self) -> PResult
<'a
, Ident
> {
867 let error_msg
= "crate name using dashes are not valid in `extern crate` statements";
868 let suggestion_msg
= "if the original crate name uses dashes you need to use underscores \
870 let mut ident
= if self.token
.is_keyword(kw
::SelfLower
) {
871 self.parse_path_segment_ident()
875 let mut idents
= vec
![];
876 let mut replacement
= vec
![];
877 let mut fixed_crate_name
= false;
878 // Accept `extern crate name-like-this` for better diagnostics.
879 let dash
= token
::BinOp(token
::BinOpToken
::Minus
);
880 if self.token
== dash
{
881 // Do not include `-` as part of the expected tokens list.
882 while self.eat(&dash
) {
883 fixed_crate_name
= true;
884 replacement
.push((self.prev_token
.span
, "_".to_string()));
885 idents
.push(self.parse_ident()?
);
888 if fixed_crate_name
{
889 let fixed_name_sp
= ident
.span
.to(idents
.last().unwrap().span
);
890 let mut fixed_name
= format
!("{}", ident
.name
);
892 fixed_name
.push_str(&format
!("_{}", part
.name
));
894 ident
= Ident
::from_str_and_span(&fixed_name
, fixed_name_sp
);
896 self.struct_span_err(fixed_name_sp
, error_msg
)
897 .span_label(fixed_name_sp
, "dash-separated idents are not valid")
898 .multipart_suggestion(suggestion_msg
, replacement
, Applicability
::MachineApplicable
)
904 /// Parses `extern` for foreign ABIs modules.
906 /// `extern` is expected to have been consumed before calling this method.
910 /// ```ignore (only-for-syntax-highlight)
914 fn parse_item_foreign_mod(
916 attrs
: &mut Vec
<Attribute
>,
918 ) -> PResult
<'a
, ItemInfo
> {
919 let abi
= self.parse_abi(); // ABI?
920 let items
= self.parse_item_list(attrs
, |p
| p
.parse_foreign_item())?
;
921 let module
= ast
::ForeignMod { unsafety, abi, items }
;
922 Ok((Ident
::invalid(), ItemKind
::ForeignMod(module
)))
925 /// Parses a foreign item (one in an `extern { ... }` block).
926 pub fn parse_foreign_item(&mut self) -> PResult
<'a
, Option
<Option
<P
<ForeignItem
>>>> {
927 Ok(self.parse_item_(|_
| true, ForceCollect
::No
)?
.map(
928 |Item { attrs, id, span, vis, ident, kind, tokens }
| {
929 let kind
= match ForeignItemKind
::try_from(kind
) {
931 Err(kind
) => match kind
{
932 ItemKind
::Const(_
, a
, b
) => {
933 self.error_on_foreign_const(span
, ident
);
934 ForeignItemKind
::Static(a
, Mutability
::Not
, b
)
936 _
=> return self.error_bad_item_kind(span
, &kind
, "`extern` blocks"),
939 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }
))
944 fn error_bad_item_kind
<T
>(&self, span
: Span
, kind
: &ItemKind
, ctx
: &str) -> Option
<T
> {
945 let span
= self.sess
.source_map().guess_head_span(span
);
946 let descr
= kind
.descr();
947 self.struct_span_err(span
, &format
!("{} is not supported in {}", descr
, ctx
))
948 .help(&format
!("consider moving the {} out to a nearby module scope", descr
))
953 fn error_on_foreign_const(&self, span
: Span
, ident
: Ident
) {
954 self.struct_span_err(ident
.span
, "extern items cannot be `const`")
956 span
.with_hi(ident
.span
.lo()),
957 "try using a static value",
958 "static ".to_string(),
959 Applicability
::MachineApplicable
,
961 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
965 fn is_unsafe_foreign_mod(&self) -> bool
{
966 self.token
.is_keyword(kw
::Unsafe
)
967 && self.is_keyword_ahead(1, &[kw
::Extern
])
969 2 + self.look_ahead(2, |t
| t
.can_begin_literal_maybe_minus() as usize),
970 |t
| t
.kind
== token
::OpenDelim(token
::Brace
),
974 fn is_static_global(&mut self) -> bool
{
975 if self.check_keyword(kw
::Static
) {
976 // Check if this could be a closure.
977 !self.look_ahead(1, |token
| {
978 if token
.is_keyword(kw
::Move
) {
981 matches
!(token
.kind
, token
::BinOp(token
::Or
) | token
::OrOr
)
988 /// Recover on `const mut` with `const` already eaten.
989 fn recover_const_mut(&mut self, const_span
: Span
) {
990 if self.eat_keyword(kw
::Mut
) {
991 let span
= self.prev_token
.span
;
992 self.struct_span_err(span
, "const globals cannot be mutable")
993 .span_label(span
, "cannot be mutable")
996 "you might want to declare a static instead",
998 Applicability
::MaybeIncorrect
,
1004 /// Recover on `const impl` with `const` already eaten.
1005 fn recover_const_impl(
1008 attrs
: &mut Vec
<Attribute
>,
1009 defaultness
: Defaultness
,
1010 ) -> PResult
<'a
, ItemInfo
> {
1011 let impl_span
= self.token
.span
;
1012 let mut err
= self.expected_ident_found();
1014 // Only try to recover if this is implementing a trait for a type
1015 let mut impl_info
= match self.parse_item_impl(attrs
, defaultness
) {
1016 Ok(impl_info
) => impl_info
,
1017 Err(mut recovery_error
) => {
1018 // Recovery failed, raise the "expected identifier" error
1019 recovery_error
.cancel();
1025 ItemKind
::Impl(box ImplKind
{
1026 of_trait
: Some(ref trai
), ref mut constness
, ..
1028 *constness
= Const
::Yes(const_span
);
1030 let before_trait
= trai
.path
.span
.shrink_to_lo();
1031 let const_up_to_impl
= const_span
.with_hi(impl_span
.lo());
1032 err
.multipart_suggestion(
1033 "you might have meant to write a const trait impl",
1034 vec
![(const_up_to_impl
, "".to_owned()), (before_trait
, "const ".to_owned())],
1035 Applicability
::MaybeIncorrect
,
1039 ItemKind
::Impl { .. }
=> return Err(err
),
1040 _
=> unreachable
!(),
1046 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1047 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1049 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1050 fn parse_item_global(
1052 m
: Option
<Mutability
>,
1053 ) -> PResult
<'a
, (Ident
, P
<Ty
>, Option
<P
<ast
::Expr
>>)> {
1054 let id
= if m
.is_none() { self.parse_ident_or_underscore() }
else { self.parse_ident() }?
;
1056 // Parse the type of a `const` or `static mut?` item.
1057 // That is, the `":" $ty` fragment.
1058 let ty
= if self.eat(&token
::Colon
) {
1061 self.recover_missing_const_type(id
, m
)
1064 let expr
= if self.eat(&token
::Eq
) { Some(self.parse_expr()?) }
else { None }
;
1065 self.expect_semi()?
;
1069 /// We were supposed to parse `:` but the `:` was missing.
1070 /// This means that the type is missing.
1071 fn recover_missing_const_type(&mut self, id
: Ident
, m
: Option
<Mutability
>) -> P
<Ty
> {
1072 // Construct the error and stash it away with the hope
1073 // that typeck will later enrich the error with a type.
1074 let kind
= match m
{
1075 Some(Mutability
::Mut
) => "static mut",
1076 Some(Mutability
::Not
) => "static",
1079 let mut err
= self.struct_span_err(id
.span
, &format
!("missing type for `{}` item", kind
));
1080 err
.span_suggestion(
1082 "provide a type for the item",
1083 format
!("{}: <type>", id
),
1084 Applicability
::HasPlaceholders
,
1086 err
.stash(id
.span
, StashKey
::ItemNoType
);
1088 // The user intended that the type be inferred,
1089 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1090 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None }
)
1093 /// Parses an enum declaration.
1094 fn parse_item_enum(&mut self) -> PResult
<'a
, ItemInfo
> {
1095 let id
= self.parse_ident()?
;
1096 let mut generics
= self.parse_generics()?
;
1097 generics
.where_clause
= self.parse_where_clause()?
;
1100 self.parse_delim_comma_seq(token
::Brace
, |p
| p
.parse_enum_variant()).map_err(|e
| {
1101 self.recover_stmt();
1105 let enum_definition
=
1106 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() }
;
1107 Ok((id
, ItemKind
::Enum(enum_definition
, generics
)))
1110 fn parse_enum_variant(&mut self) -> PResult
<'a
, Option
<Variant
>> {
1111 let variant_attrs
= self.parse_outer_attributes()?
;
1112 let vlo
= self.token
.span
;
1114 let vis
= self.parse_visibility(FollowedByType
::No
)?
;
1115 if !self.recover_nested_adt_item(kw
::Enum
)?
{
1118 let ident
= self.parse_ident()?
;
1120 let struct_def
= if self.check(&token
::OpenDelim(token
::Brace
)) {
1121 // Parse a struct variant.
1122 let (fields
, recovered
) = self.parse_record_struct_body()?
;
1123 VariantData
::Struct(fields
, recovered
)
1124 } else if self.check(&token
::OpenDelim(token
::Paren
)) {
1125 VariantData
::Tuple(self.parse_tuple_struct_body()?
, DUMMY_NODE_ID
)
1127 VariantData
::Unit(DUMMY_NODE_ID
)
1131 if self.eat(&token
::Eq
) { Some(self.parse_anon_const_expr()?) }
else { None }
;
1133 let vr
= ast
::Variant
{
1137 attrs
: variant_attrs
,
1140 span
: vlo
.to(self.prev_token
.span
),
1141 is_placeholder
: false,
1147 /// Parses `struct Foo { ... }`.
1148 fn parse_item_struct(&mut self) -> PResult
<'a
, ItemInfo
> {
1149 let class_name
= self.parse_ident()?
;
1151 let mut generics
= self.parse_generics()?
;
1153 // There is a special case worth noting here, as reported in issue #17904.
1154 // If we are parsing a tuple struct it is the case that the where clause
1155 // should follow the field list. Like so:
1157 // struct Foo<T>(T) where T: Copy;
1159 // If we are parsing a normal record-style struct it is the case
1160 // that the where clause comes before the body, and after the generics.
1161 // So if we look ahead and see a brace or a where-clause we begin
1162 // parsing a record style struct.
1164 // Otherwise if we look ahead and see a paren we parse a tuple-style
1167 let vdata
= if self.token
.is_keyword(kw
::Where
) {
1168 generics
.where_clause
= self.parse_where_clause()?
;
1169 if self.eat(&token
::Semi
) {
1170 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1171 VariantData
::Unit(DUMMY_NODE_ID
)
1173 // If we see: `struct Foo<T> where T: Copy { ... }`
1174 let (fields
, recovered
) = self.parse_record_struct_body()?
;
1175 VariantData
::Struct(fields
, recovered
)
1177 // No `where` so: `struct Foo<T>;`
1178 } else if self.eat(&token
::Semi
) {
1179 VariantData
::Unit(DUMMY_NODE_ID
)
1180 // Record-style struct definition
1181 } else if self.token
== token
::OpenDelim(token
::Brace
) {
1182 let (fields
, recovered
) = self.parse_record_struct_body()?
;
1183 VariantData
::Struct(fields
, recovered
)
1184 // Tuple-style struct definition with optional where-clause.
1185 } else if self.token
== token
::OpenDelim(token
::Paren
) {
1186 let body
= VariantData
::Tuple(self.parse_tuple_struct_body()?
, DUMMY_NODE_ID
);
1187 generics
.where_clause
= self.parse_where_clause()?
;
1188 self.expect_semi()?
;
1191 let token_str
= super::token_descr(&self.token
);
1193 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1196 let mut err
= self.struct_span_err(self.token
.span
, msg
);
1197 err
.span_label(self.token
.span
, "expected `where`, `{`, `(`, or `;` after struct name");
1201 Ok((class_name
, ItemKind
::Struct(vdata
, generics
)))
1204 /// Parses `union Foo { ... }`.
1205 fn parse_item_union(&mut self) -> PResult
<'a
, ItemInfo
> {
1206 let class_name
= self.parse_ident()?
;
1208 let mut generics
= self.parse_generics()?
;
1210 let vdata
= if self.token
.is_keyword(kw
::Where
) {
1211 generics
.where_clause
= self.parse_where_clause()?
;
1212 let (fields
, recovered
) = self.parse_record_struct_body()?
;
1213 VariantData
::Struct(fields
, recovered
)
1214 } else if self.token
== token
::OpenDelim(token
::Brace
) {
1215 let (fields
, recovered
) = self.parse_record_struct_body()?
;
1216 VariantData
::Struct(fields
, recovered
)
1218 let token_str
= super::token_descr(&self.token
);
1219 let msg
= &format
!("expected `where` or `{{` after union name, found {}", token_str
);
1220 let mut err
= self.struct_span_err(self.token
.span
, msg
);
1221 err
.span_label(self.token
.span
, "expected `where` or `{` after union name");
1225 Ok((class_name
, ItemKind
::Union(vdata
, generics
)))
1228 fn parse_record_struct_body(
1230 ) -> PResult
<'a
, (Vec
<StructField
>, /* recovered */ bool
)> {
1231 let mut fields
= Vec
::new();
1232 let mut recovered
= false;
1233 if self.eat(&token
::OpenDelim(token
::Brace
)) {
1234 while self.token
!= token
::CloseDelim(token
::Brace
) {
1235 let field
= self.parse_struct_decl_field().map_err(|e
| {
1236 self.consume_block(token
::Brace
, ConsumeClosingDelim
::No
);
1241 Ok(field
) => fields
.push(field
),
1248 self.eat(&token
::CloseDelim(token
::Brace
));
1250 let token_str
= super::token_descr(&self.token
);
1251 let msg
= &format
!("expected `where`, or `{{` after struct name, found {}", token_str
);
1252 let mut err
= self.struct_span_err(self.token
.span
, msg
);
1253 err
.span_label(self.token
.span
, "expected `where`, or `{` after struct name");
1257 Ok((fields
, recovered
))
1260 fn parse_tuple_struct_body(&mut self) -> PResult
<'a
, Vec
<StructField
>> {
1261 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1262 // Unit like structs are handled in parse_item_struct function
1263 self.parse_paren_comma_seq(|p
| {
1264 let attrs
= p
.parse_outer_attributes()?
;
1265 let lo
= p
.token
.span
;
1266 let vis
= p
.parse_visibility(FollowedByType
::Yes
)?
;
1267 let ty
= p
.parse_ty()?
;
1269 span
: lo
.to(ty
.span
),
1275 is_placeholder
: false,
1281 /// Parses an element of a struct declaration.
1282 fn parse_struct_decl_field(&mut self) -> PResult
<'a
, StructField
> {
1283 let attrs
= self.parse_outer_attributes()?
;
1284 let lo
= self.token
.span
;
1285 let vis
= self.parse_visibility(FollowedByType
::No
)?
;
1286 self.parse_single_struct_field(lo
, vis
, attrs
)
1289 /// Parses a structure field declaration.
1290 fn parse_single_struct_field(
1294 attrs
: Vec
<Attribute
>,
1295 ) -> PResult
<'a
, StructField
> {
1296 let mut seen_comma
: bool
= false;
1297 let a_var
= self.parse_name_and_ty(lo
, vis
, attrs
)?
;
1298 if self.token
== token
::Comma
{
1301 match self.token
.kind
{
1305 token
::CloseDelim(token
::Brace
) => {}
1306 token
::DocComment(..) => {
1307 let previous_span
= self.prev_token
.span
;
1308 let mut err
= self.span_fatal_err(self.token
.span
, Error
::UselessDocComment
);
1309 self.bump(); // consume the doc comment
1310 let comma_after_doc_seen
= self.eat(&token
::Comma
);
1311 // `seen_comma` is always false, because we are inside doc block
1312 // condition is here to make code more readable
1313 if !seen_comma
&& comma_after_doc_seen
{
1316 if comma_after_doc_seen
|| self.token
== token
::CloseDelim(token
::Brace
) {
1320 let sp
= self.sess
.source_map().next_point(previous_span
);
1321 err
.span_suggestion(
1323 "missing comma here",
1325 Applicability
::MachineApplicable
,
1332 let sp
= self.prev_token
.span
.shrink_to_hi();
1333 let mut err
= self.struct_span_err(
1335 &format
!("expected `,`, or `}}`, found {}", super::token_descr(&self.token
)),
1338 // Try to recover extra trailing angle brackets
1339 let mut recovered
= false;
1340 if let TyKind
::Path(_
, Path { segments, .. }
) = &a_var
.ty
.kind
{
1341 if let Some(last_segment
) = segments
.last() {
1342 recovered
= self.check_trailing_angle_brackets(
1344 &[&token
::Comma
, &token
::CloseDelim(token
::Brace
)],
1347 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1349 self.eat(&token
::Comma
);
1350 // `check_trailing_angle_brackets` already emitted a nicer error
1356 if self.token
.is_ident() {
1357 // This is likely another field; emit the diagnostic and keep going
1358 err
.span_suggestion(
1360 "try adding a comma",
1362 Applicability
::MachineApplicable
,
1369 // Make sure an error was emitted (either by recovering an angle bracket,
1370 // or by finding an identifier as the next token), since we're
1371 // going to continue parsing
1372 assert
!(self.sess
.span_diagnostic
.has_errors());
1381 /// Parses a structure field.
1382 fn parse_name_and_ty(
1386 attrs
: Vec
<Attribute
>,
1387 ) -> PResult
<'a
, StructField
> {
1388 let name
= self.parse_ident_common(false)?
;
1389 self.expect(&token
::Colon
)?
;
1390 let ty
= self.parse_ty()?
;
1392 span
: lo
.to(self.prev_token
.span
),
1398 is_placeholder
: false,
1402 /// Parses a declarative macro 2.0 definition.
1403 /// The `macro` keyword has already been parsed.
1405 /// MacBody = "{" TOKEN_STREAM "}" ;
1406 /// MacParams = "(" TOKEN_STREAM ")" ;
1407 /// DeclMac = "macro" Ident MacParams? MacBody ;
1409 fn parse_item_decl_macro(&mut self, lo
: Span
) -> PResult
<'a
, ItemInfo
> {
1410 let ident
= self.parse_ident()?
;
1411 let body
= if self.check(&token
::OpenDelim(token
::Brace
)) {
1412 self.parse_mac_args()?
// `MacBody`
1413 } else if self.check(&token
::OpenDelim(token
::Paren
)) {
1414 let params
= self.parse_token_tree(); // `MacParams`
1415 let pspan
= params
.span();
1416 if !self.check(&token
::OpenDelim(token
::Brace
)) {
1417 return self.unexpected();
1419 let body
= self.parse_token_tree(); // `MacBody`
1420 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1421 let bspan
= body
.span();
1422 let arrow
= TokenTree
::token(token
::FatArrow
, pspan
.between(bspan
)); // `=>`
1423 let tokens
= TokenStream
::new(vec
![params
.into(), arrow
.into(), body
.into()]);
1424 let dspan
= DelimSpan
::from_pair(pspan
.shrink_to_lo(), bspan
.shrink_to_hi());
1425 P(MacArgs
::Delimited(dspan
, MacDelimiter
::Brace
, tokens
))
1427 return self.unexpected();
1430 self.sess
.gated_spans
.gate(sym
::decl_macro
, lo
.to(self.prev_token
.span
));
1431 Ok((ident
, ItemKind
::MacroDef(ast
::MacroDef { body, macro_rules: false }
)))
1434 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1435 fn is_macro_rules_item(&mut self) -> bool
{
1436 self.check_keyword(kw
::MacroRules
)
1437 && self.look_ahead(1, |t
| *t
== token
::Not
)
1438 && self.look_ahead(2, |t
| t
.is_ident())
1441 /// Parses a `macro_rules! foo { ... }` declarative macro.
1442 fn parse_item_macro_rules(&mut self, vis
: &Visibility
) -> PResult
<'a
, ItemInfo
> {
1443 self.expect_keyword(kw
::MacroRules
)?
; // `macro_rules`
1444 self.expect(&token
::Not
)?
; // `!`
1446 let ident
= self.parse_ident()?
;
1447 let body
= self.parse_mac_args()?
;
1448 self.eat_semi_for_macro_if_needed(&body
);
1449 self.complain_if_pub_macro(vis
, true);
1451 Ok((ident
, ItemKind
::MacroDef(ast
::MacroDef { body, macro_rules: true }
)))
1454 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1455 /// If that's not the case, emit an error.
1456 fn complain_if_pub_macro(&self, vis
: &Visibility
, macro_rules
: bool
) {
1457 if let VisibilityKind
::Inherited
= vis
.kind
{
1461 let vstr
= pprust
::vis_to_string(vis
);
1462 let vstr
= vstr
.trim_end();
1464 let msg
= format
!("can't qualify macro_rules invocation with `{}`", vstr
);
1465 self.struct_span_err(vis
.span
, &msg
)
1468 "try exporting the macro",
1469 "#[macro_export]".to_owned(),
1470 Applicability
::MaybeIncorrect
, // speculative
1474 self.struct_span_err(vis
.span
, "can't qualify macro invocation with `pub`")
1477 "remove the visibility",
1479 Applicability
::MachineApplicable
,
1481 .help(&format
!("try adjusting the macro to put `{}` inside the invocation", vstr
))
1486 fn eat_semi_for_macro_if_needed(&mut self, args
: &MacArgs
) {
1487 if args
.need_semicolon() && !self.eat(&token
::Semi
) {
1488 self.report_invalid_macro_expansion_item(args
);
1492 fn report_invalid_macro_expansion_item(&self, args
: &MacArgs
) {
1493 let span
= args
.span().expect("undelimited macro call");
1494 let mut err
= self.struct_span_err(
1496 "macros that expand to items must be delimited with braces or followed by a semicolon",
1498 if self.unclosed_delims
.is_empty() {
1499 let DelimSpan { open, close }
= match args
{
1500 MacArgs
::Empty
| MacArgs
::Eq(..) => unreachable
!(),
1501 MacArgs
::Delimited(dspan
, ..) => *dspan
,
1503 err
.multipart_suggestion(
1504 "change the delimiters to curly braces",
1505 vec
![(open
, "{".to_string()), (close, '}'.to_string())],
1506 Applicability::MaybeIncorrect,
1509 err.span_suggestion(
1511 "change the delimiters to curly braces
",
1512 " { /* items */ }
".to_string(),
1513 Applicability::HasPlaceholders,
1516 err.span_suggestion(
1517 span.shrink_to_hi(),
1520 Applicability::MaybeIncorrect,
1525 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1526 /// it is, we try to parse the item and report error about nested types.
1527 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1528 if (self.token.is_keyword(kw::Enum)
1529 || self.token.is_keyword(kw::Struct)
1530 || self.token.is_keyword(kw::Union))
1531 && self.look_ahead(1, |t| t.is_ident())
1533 let kw_token = self.token.clone();
1534 let kw_str = pprust::token_to_string(&kw_token);
1535 let item = self.parse_item(ForceCollect::No)?;
1537 self.struct_span_err(
1539 &format!("`{}` definition cannot be nested inside `{}`
", kw_str, keyword),
1543 &format!("consider creating a new `{}` definition instead of nesting
", kw_str),
1545 Applicability::MaybeIncorrect,
1548 // We successfully parsed the item but we must inform the caller about nested problem.
1555 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1557 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1558 type ReqName = fn(Edition) -> bool;
1560 /// Parsing of functions and methods.
1561 impl<'a> Parser<'a> {
1562 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1565 attrs: &mut Vec<Attribute>,
1568 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1569 let header = self.parse_fn_front_matter()?; // `const ... fn`
1570 let ident = self.parse_ident()?; // `foo`
1571 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1572 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1573 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1575 let mut sig_hi = self.prev_token.span;
1576 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi)?; // `;` or `{ ... }`.
1577 let fn_sig_span = sig_lo.to(sig_hi);
1578 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1581 /// Parse the "body
" of a function.
1582 /// This can either be `;` when there's no body,
1583 /// or e.g. a block when the function is a provided one.
1586 attrs: &mut Vec<Attribute>,
1589 ) -> PResult<'a, Option<P<Block>>> {
1590 let (inner_attrs, body) = if self.eat(&token::Semi) {
1591 // Include the trailing semicolon in the span of the signature
1592 *sig_hi = self.prev_token.span;
1594 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1595 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1596 } else if self.token.kind == token::Eq {
1597 // Recover `fn foo() = $expr;`.
1599 let eq_sp = self.prev_token.span;
1600 let _ = self.parse_expr()?;
1601 self.expect_semi()?; // `;`
1602 let span = eq_sp.to(self.prev_token.span);
1603 self.struct_span_err(span, "function body cannot be `
= expression
;`
")
1604 .multipart_suggestion(
1605 "surround the expression with `{` and `}` instead of `
=` and `
;`
",
1606 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }
".to_string())],
1607 Applicability::MachineApplicable,
1610 (Vec::new(), Some(self.mk_block_err(span)))
1612 if let Err(mut err) =
1613 self.expected_one_of_not_found(&[], &[token::Semi, token::OpenDelim(token::Brace)])
1615 if self.token.kind == token::CloseDelim(token::Brace) {
1616 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1617 // the AST for typechecking.
1618 err.span_label(ident.span, "while parsing this `
fn`
");
1628 attrs.extend(inner_attrs);
1632 /// Is the current token the start of an `FnHeader` / not a valid parse?
1633 pub(super) fn check_fn_front_matter(&mut self) -> bool {
1634 // We use an over-approximation here.
1635 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1636 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1637 self.check_keyword(kw::Fn) // Definitely an `fn`.
1638 // `$qual fn` or `$qual $qual`:
1639 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1640 && self.look_ahead(1, |t| {
1641 // `$qual fn`, e.g. `const fn` or `async fn`.
1642 t.is_keyword(kw::Fn)
1643 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1644 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name)
1645 // Rule out 2015 `const async: T = val`.
1647 // Rule out unsafe extern block.
1648 && !self.is_unsafe_foreign_mod())
1651 || self.check_keyword(kw::Extern)
1652 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1653 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1656 /// Parses all the "front matter
" (or "qualifiers
") for a `fn` declaration,
1657 /// up to and including the `fn` keyword. The formal grammar is:
1660 /// Extern = "extern" StringLit? ;
1661 /// FnQual = "const"? "async
"? "unsafe"? Extern? ;
1662 /// FnFrontMatter = FnQual "fn" ;
1664 pub(super) fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1665 let constness = self.parse_constness();
1666 let asyncness = self.parse_asyncness();
1667 let unsafety = self.parse_unsafety();
1668 let ext = self.parse_extern()?;
1670 if let Async::Yes { span, .. } = asyncness {
1671 self.ban_async_in_2015(span);
1674 if !self.eat_keyword(kw::Fn) {
1675 // It is possible for `expect_one_of` to recover given the contents of
1676 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1677 // account for this.
1678 if !self.expect_one_of(&[], &[])? {
1683 Ok(FnHeader { constness, unsafety, asyncness, ext })
1686 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1687 fn ban_async_in_2015(&self, span: Span) {
1688 if span.rust_2015() {
1689 let diag = self.diagnostic();
1690 struct_span_err!(diag, span, E0670, "`async
fn` is not permitted
in Rust
2015")
1691 .span_label(span, "to
use `async
fn`
, switch to Rust
2018 or later
")
1692 .help(&format!("set `edition
= \"{}
\"`
in `Cargo
.toml`
", LATEST_STABLE_EDITION))
1693 .note("for more on editions
, read https
://doc.rust-lang.org/edition-guide")
1698 /// Parses the parameter list and result type of a function declaration.
1699 pub(super) fn parse_fn_decl(
1702 ret_allow_plus
: AllowPlus
,
1703 recover_return_sign
: RecoverReturnSign
,
1704 ) -> PResult
<'a
, P
<FnDecl
>> {
1706 inputs
: self.parse_fn_params(req_name
)?
,
1707 output
: self.parse_ret_ty(ret_allow_plus
, RecoverQPath
::Yes
, recover_return_sign
)?
,
1711 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1712 fn parse_fn_params(&mut self, req_name
: ReqName
) -> PResult
<'a
, Vec
<Param
>> {
1713 let mut first_param
= true;
1714 // Parse the arguments, starting out with `self` being allowed...
1715 let (mut params
, _
) = self.parse_paren_comma_seq(|p
| {
1716 let param
= p
.parse_param_general(req_name
, first_param
).or_else(|mut e
| {
1718 let lo
= p
.prev_token
.span
;
1719 // Skip every token until next possible arg or end.
1720 p
.eat_to_tokens(&[&token
::Comma
, &token
::CloseDelim(token
::Paren
)]);
1721 // Create a placeholder argument for proper arg count (issue #34264).
1722 Ok(dummy_arg(Ident
::new(kw
::Empty
, lo
.to(p
.prev_token
.span
))))
1724 // ...now that we've parsed the first argument, `self` is no longer allowed.
1725 first_param
= false;
1728 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1729 self.deduplicate_recovered_params_names(&mut params
);
1733 /// Parses a single function parameter.
1735 /// - `self` is syntactically allowed when `first_param` holds.
1736 fn parse_param_general(&mut self, req_name
: ReqName
, first_param
: bool
) -> PResult
<'a
, Param
> {
1737 let lo
= self.token
.span
;
1738 let attrs
= self.parse_outer_attributes()?
;
1740 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1741 if let Some(mut param
) = self.parse_self_param()?
{
1742 param
.attrs
= attrs
.into();
1743 return if first_param { Ok(param) }
else { self.recover_bad_self_param(param) }
;
1746 let is_name_required
= match self.token
.kind
{
1747 token
::DotDotDot
=> false,
1748 _
=> req_name(self.token
.span
.edition()),
1750 let (pat
, ty
) = if is_name_required
|| self.is_named_param() {
1751 debug
!("parse_param_general parse_pat (is_name_required:{})", is_name_required
);
1753 let pat
= self.parse_fn_param_pat()?
;
1754 if let Err(mut err
) = self.expect(&token
::Colon
) {
1755 return if let Some(ident
) =
1756 self.parameter_without_type(&mut err
, pat
, is_name_required
, first_param
)
1759 Ok(dummy_arg(ident
))
1765 self.eat_incorrect_doc_comment_for_param_type();
1766 (pat
, self.parse_ty_for_param()?
)
1768 debug
!("parse_param_general ident_to_pat");
1769 let parser_snapshot_before_ty
= self.clone();
1770 self.eat_incorrect_doc_comment_for_param_type();
1771 let mut ty
= self.parse_ty_for_param();
1773 && self.token
!= token
::Comma
1774 && self.token
!= token
::CloseDelim(token
::Paren
)
1776 // This wasn't actually a type, but a pattern looking like a type,
1777 // so we are going to rollback and re-parse for recovery.
1778 ty
= self.unexpected();
1782 let ident
= Ident
::new(kw
::Empty
, self.prev_token
.span
);
1783 let bm
= BindingMode
::ByValue(Mutability
::Not
);
1784 let pat
= self.mk_pat_ident(ty
.span
, bm
, ident
);
1787 // If this is a C-variadic argument and we hit an error, return the error.
1788 Err(err
) if self.token
== token
::DotDotDot
=> return Err(err
),
1789 // Recover from attempting to parse the argument as a type without pattern.
1792 *self = parser_snapshot_before_ty
;
1793 self.recover_arg_parse()?
1798 let span
= lo
.until(self.token
.span
);
1801 attrs
: attrs
.into(),
1802 id
: ast
::DUMMY_NODE_ID
,
1803 is_placeholder
: false,
1810 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1811 fn parse_self_param(&mut self) -> PResult
<'a
, Option
<Param
>> {
1812 // Extract an identifier *after* having confirmed that the token is one.
1813 let expect_self_ident
= |this
: &mut Self| match this
.token
.ident() {
1814 Some((ident
, false)) => {
1818 _
=> unreachable
!(),
1820 // Is `self` `n` tokens ahead?
1821 let is_isolated_self
= |this
: &Self, n
| {
1822 this
.is_keyword_ahead(n
, &[kw
::SelfLower
])
1823 && this
.look_ahead(n
+ 1, |t
| t
!= &token
::ModSep
)
1825 // Is `mut self` `n` tokens ahead?
1826 let is_isolated_mut_self
=
1827 |this
: &Self, n
| this
.is_keyword_ahead(n
, &[kw
::Mut
]) && is_isolated_self(this
, n
+ 1);
1828 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1829 let parse_self_possibly_typed
= |this
: &mut Self, m
| {
1830 let eself_ident
= expect_self_ident(this
);
1831 let eself_hi
= this
.prev_token
.span
;
1832 let eself
= if this
.eat(&token
::Colon
) {
1833 SelfKind
::Explicit(this
.parse_ty()?
, m
)
1837 Ok((eself
, eself_ident
, eself_hi
))
1839 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1840 let recover_self_ptr
= |this
: &mut Self| {
1841 let msg
= "cannot pass `self` by raw pointer";
1842 let span
= this
.token
.span
;
1843 this
.struct_span_err(span
, msg
).span_label(span
, msg
).emit();
1845 Ok((SelfKind
::Value(Mutability
::Not
), expect_self_ident(this
), this
.prev_token
.span
))
1848 // Parse optional `self` parameter of a method.
1849 // Only a limited set of initial token sequences is considered `self` parameters; anything
1850 // else is parsed as a normal function parameter list, so some lookahead is required.
1851 let eself_lo
= self.token
.span
;
1852 let (eself
, eself_ident
, eself_hi
) = match self.token
.uninterpolate().kind
{
1853 token
::BinOp(token
::And
) => {
1854 let eself
= if is_isolated_self(self, 1) {
1857 SelfKind
::Region(None
, Mutability
::Not
)
1858 } else if is_isolated_mut_self(self, 1) {
1862 SelfKind
::Region(None
, Mutability
::Mut
)
1863 } else if self.look_ahead(1, |t
| t
.is_lifetime()) && is_isolated_self(self, 2) {
1866 let lt
= self.expect_lifetime();
1867 SelfKind
::Region(Some(lt
), Mutability
::Not
)
1868 } else if self.look_ahead(1, |t
| t
.is_lifetime()) && is_isolated_mut_self(self, 2) {
1871 let lt
= self.expect_lifetime();
1873 SelfKind
::Region(Some(lt
), Mutability
::Mut
)
1878 (eself
, expect_self_ident(self), self.prev_token
.span
)
1881 token
::BinOp(token
::Star
) if is_isolated_self(self, 1) => {
1883 recover_self_ptr(self)?
1885 // `*mut self` and `*const self`
1886 token
::BinOp(token
::Star
)
1887 if self.look_ahead(1, |t
| t
.is_mutability()) && is_isolated_self(self, 2) =>
1891 recover_self_ptr(self)?
1893 // `self` and `self: TYPE`
1894 token
::Ident(..) if is_isolated_self(self, 0) => {
1895 parse_self_possibly_typed(self, Mutability
::Not
)?
1897 // `mut self` and `mut self: TYPE`
1898 token
::Ident(..) if is_isolated_mut_self(self, 0) => {
1900 parse_self_possibly_typed(self, Mutability
::Mut
)?
1902 _
=> return Ok(None
),
1905 let eself
= source_map
::respan(eself_lo
.to(eself_hi
), eself
);
1906 Ok(Some(Param
::from_self(AttrVec
::default(), eself
, eself_ident
)))
1909 fn is_named_param(&self) -> bool
{
1910 let offset
= match self.token
.kind
{
1911 token
::Interpolated(ref nt
) => match **nt
{
1912 token
::NtPat(..) => return self.look_ahead(1, |t
| t
== &token
::Colon
),
1915 token
::BinOp(token
::And
) | token
::AndAnd
=> 1,
1916 _
if self.token
.is_keyword(kw
::Mut
) => 1,
1920 self.look_ahead(offset
, |t
| t
.is_ident())
1921 && self.look_ahead(offset
+ 1, |t
| t
== &token
::Colon
)
1924 fn recover_first_param(&mut self) -> &'
static str {
1926 .parse_outer_attributes()
1927 .and_then(|_
| self.parse_self_param())
1928 .map_err(|mut e
| e
.cancel())
1930 Ok(Some(_
)) => "method",