1 use super::diagnostics
::{dummy_arg, ConsumeClosingDelim, Error}
;
2 use super::ty
::{AllowPlus, RecoverQPath, RecoverReturnSign}
;
3 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken}
;
7 use rustc_ast
::token
::{self, TokenKind}
;
8 use rustc_ast
::tokenstream
::{DelimSpan, TokenStream, TokenTree}
;
9 use rustc_ast
::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID}
;
10 use rustc_ast
::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind}
;
11 use rustc_ast
::{BindingMode, Block, FnDecl, FnSig, Param, SelfKind}
;
12 use rustc_ast
::{EnumDef, FieldDef, Generics, TraitRef, Ty, TyKind, Variant, VariantData}
;
13 use rustc_ast
::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind}
;
14 use rustc_ast
::{MacArgs, MacCall, MacDelimiter}
;
15 use rustc_ast_pretty
::pprust
;
16 use rustc_errors
::{struct_span_err, Applicability, PResult, StashKey}
;
17 use rustc_span
::edition
::Edition
;
18 use rustc_span
::lev_distance
::lev_distance
;
19 use rustc_span
::source_map
::{self, Span}
;
20 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
21 use rustc_span
::DUMMY_SP
;
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 (attrs
, items
, spans
) = self.parse_mod(&token
::Eof
)?
;
31 Ok(ast
::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false }
)
34 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
35 fn parse_item_mod(&mut self, attrs
: &mut Vec
<Attribute
>) -> PResult
<'a
, ItemInfo
> {
36 let unsafety
= self.parse_unsafety();
37 self.expect_keyword(kw
::Mod
)?
;
38 let id
= self.parse_ident()?
;
39 let mod_kind
= if self.eat(&token
::Semi
) {
42 self.expect(&token
::OpenDelim(token
::Brace
))?
;
43 let (mut inner_attrs
, items
, inner_span
) =
44 self.parse_mod(&token
::CloseDelim(token
::Brace
))?
;
45 attrs
.append(&mut inner_attrs
);
46 ModKind
::Loaded(items
, Inline
::Yes
, inner_span
)
48 Ok((id
, ItemKind
::Mod(unsafety
, mod_kind
)))
51 /// Parses the contents of a module (inner attributes followed by module items).
55 ) -> PResult
<'a
, (Vec
<Attribute
>, Vec
<P
<Item
>>, ModSpans
)> {
56 let lo
= self.token
.span
;
57 let attrs
= self.parse_inner_attributes()?
;
59 let post_attr_lo
= self.token
.span
;
60 let mut items
= vec
![];
61 while let Some(item
) = self.parse_item(ForceCollect
::No
)?
{
63 self.maybe_consume_incorrect_semicolon(&items
);
67 let token_str
= super::token_descr(&self.token
);
68 if !self.maybe_consume_incorrect_semicolon(&items
) {
69 let msg
= &format
!("expected item, found {token_str}");
70 let mut err
= self.struct_span_err(self.token
.span
, msg
);
71 err
.span_label(self.token
.span
, "expected item");
76 let inject_use_span
= post_attr_lo
.data().with_hi(post_attr_lo
.lo());
77 let mod_spans
= ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span }
;
78 Ok((attrs
, items
, mod_spans
))
82 pub(super) type ItemInfo
= (Ident
, ItemKind
);
85 pub fn parse_item(&mut self, force_collect
: ForceCollect
) -> PResult
<'a
, Option
<P
<Item
>>> {
86 let fn_parse_mode
= FnParseMode { req_name: |_| true, req_body: true }
;
87 self.parse_item_(fn_parse_mode
, force_collect
).map(|i
| i
.map(P
))
92 fn_parse_mode
: FnParseMode
,
93 force_collect
: ForceCollect
,
94 ) -> PResult
<'a
, Option
<Item
>> {
95 let attrs
= self.parse_outer_attributes()?
;
96 self.parse_item_common(attrs
, true, false, fn_parse_mode
, force_collect
)
99 pub(super) fn parse_item_common(
104 fn_parse_mode
: FnParseMode
,
105 force_collect
: ForceCollect
,
106 ) -> PResult
<'a
, Option
<Item
>> {
107 // Don't use `maybe_whole` so that we have precise control
108 // over when we bump the parser
109 if let token
::Interpolated(nt
) = &self.token
.kind
&& let token
::NtItem(item
) = &**nt
{
110 let mut item
= item
.clone();
113 attrs
.prepend_to_nt_inner(&mut item
.attrs
);
114 return Ok(Some(item
.into_inner()));
117 let mut unclosed_delims
= vec
![];
119 self.collect_tokens_trailing_token(attrs
, force_collect
, |this
: &mut Self, attrs
| {
121 this
.parse_item_common_(attrs
, mac_allowed
, attrs_allowed
, fn_parse_mode
);
122 unclosed_delims
.append(&mut this
.unclosed_delims
);
123 Ok((item?
, TrailingToken
::None
))
126 self.unclosed_delims
.append(&mut unclosed_delims
);
130 fn parse_item_common_(
132 mut attrs
: Vec
<Attribute
>,
135 fn_parse_mode
: FnParseMode
,
136 ) -> PResult
<'a
, Option
<Item
>> {
137 let lo
= self.token
.span
;
138 let vis
= self.parse_visibility(FollowedByType
::No
)?
;
139 let mut def
= self.parse_defaultness();
141 self.parse_item_kind(&mut attrs
, mac_allowed
, lo
, &vis
, &mut def
, fn_parse_mode
)?
;
142 if let Some((ident
, kind
)) = kind
{
143 self.error_on_unconsumed_default(def
, &kind
);
144 let span
= lo
.to(self.prev_token
.span
);
145 let id
= DUMMY_NODE_ID
;
146 let item
= Item { ident, attrs, id, kind, vis, span, tokens: None }
;
147 return Ok(Some(item
));
150 // At this point, we have failed to parse an item.
151 self.error_on_unmatched_vis(&vis
);
152 self.error_on_unmatched_defaultness(def
);
154 self.recover_attrs_no_item(&attrs
)?
;
159 /// Error in-case a non-inherited visibility was parsed but no item followed.
160 fn error_on_unmatched_vis(&self, vis
: &Visibility
) {
161 if let VisibilityKind
::Inherited
= vis
.kind
{
164 let vs
= pprust
::vis_to_string(&vis
);
165 let vs
= vs
.trim_end();
166 self.struct_span_err(vis
.span
, &format
!("visibility `{vs}` is not followed by an item"))
167 .span_label(vis
.span
, "the visibility")
168 .help(&format
!("you likely meant to define an item, e.g., `{vs} fn foo() {{}}`"))
172 /// Error in-case a `default` was parsed but no item followed.
173 fn error_on_unmatched_defaultness(&self, def
: Defaultness
) {
174 if let Defaultness
::Default(sp
) = def
{
175 self.struct_span_err(sp
, "`default` is not followed by an item")
176 .span_label(sp
, "the `default` qualifier")
177 .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`")
182 /// Error in-case `default` was parsed in an in-appropriate context.
183 fn error_on_unconsumed_default(&self, def
: Defaultness
, kind
: &ItemKind
) {
184 if let Defaultness
::Default(span
) = def
{
185 let msg
= format
!("{} {} cannot be `default`", kind
.article(), kind
.descr());
186 self.struct_span_err(span
, &msg
)
187 .span_label(span
, "`default` because of this")
188 .note("only associated `fn`, `const`, and `type` items can be `default`")
193 /// Parses one of the items allowed by the flags.
196 attrs
: &mut Vec
<Attribute
>,
197 macros_allowed
: bool
,
200 def
: &mut Defaultness
,
201 fn_parse_mode
: FnParseMode
,
202 ) -> PResult
<'a
, Option
<ItemInfo
>> {
203 let def_final
= def
== &Defaultness
::Final
;
204 let mut def
= || mem
::replace(def
, Defaultness
::Final
);
206 let info
= if self.eat_keyword(kw
::Use
) {
208 let tree
= self.parse_use_tree()?
;
210 // If wildcard or glob-like brace syntax doesn't have `;`,
211 // the user may not know `*` or `{}` should be the last.
212 if let Err(mut e
) = self.expect_semi() {
214 UseTreeKind
::Glob
=> {
215 e
.note("the wildcard token must be last on the path");
217 UseTreeKind
::Nested(..) => {
218 e
.note("glob-like brace syntax must be last on the path");
225 (Ident
::empty(), ItemKind
::Use(tree
))
226 } else if self.check_fn_front_matter(def_final
) {
228 let (ident
, sig
, generics
, body
) = self.parse_fn(attrs
, fn_parse_mode
, lo
, vis
)?
;
229 (ident
, ItemKind
::Fn(Box
::new(Fn { defaultness: def(), sig, generics, body }
)))
230 } else if self.eat_keyword(kw
::Extern
) {
231 if self.eat_keyword(kw
::Crate
) {
233 self.parse_item_extern_crate()?
236 self.parse_item_foreign_mod(attrs
, Unsafe
::No
)?
238 } else if self.is_unsafe_foreign_mod() {
240 let unsafety
= self.parse_unsafety();
241 self.expect_keyword(kw
::Extern
)?
;
242 self.parse_item_foreign_mod(attrs
, unsafety
)?
243 } else if self.is_static_global() {
245 self.bump(); // `static`
246 let m
= self.parse_mutability();
247 let (ident
, ty
, expr
) = self.parse_item_global(Some(m
))?
;
248 (ident
, ItemKind
::Static(ty
, m
, expr
))
249 } else if let Const
::Yes(const_span
) = self.parse_constness() {
251 if self.token
.is_keyword(kw
::Impl
) {
252 // recover from `const impl`, suggest `impl const`
253 self.recover_const_impl(const_span
, attrs
, def())?
255 self.recover_const_mut(const_span
);
256 let (ident
, ty
, expr
) = self.parse_item_global(None
)?
;
257 (ident
, ItemKind
::Const(def(), ty
, expr
))
259 } else if self.check_keyword(kw
::Trait
) || self.check_auto_or_unsafe_trait_item() {
261 self.parse_item_trait(attrs
, lo
)?
262 } else if self.check_keyword(kw
::Impl
)
263 || self.check_keyword(kw
::Unsafe
) && self.is_keyword_ahead(1, &[kw
::Impl
])
266 self.parse_item_impl(attrs
, def())?
267 } else if self.check_keyword(kw
::Mod
)
268 || self.check_keyword(kw
::Unsafe
) && self.is_keyword_ahead(1, &[kw
::Mod
])
271 self.parse_item_mod(attrs
)?
272 } else if self.eat_keyword(kw
::Type
) {
274 self.parse_type_alias(def())?
275 } else if self.eat_keyword(kw
::Enum
) {
277 self.parse_item_enum()?
278 } else if self.eat_keyword(kw
::Struct
) {
280 self.parse_item_struct()?
281 } else if self.is_kw_followed_by_ident(kw
::Union
) {
283 self.bump(); // `union`
284 self.parse_item_union()?
285 } else if self.eat_keyword(kw
::Macro
) {
287 self.parse_item_decl_macro(lo
)?
288 } else if let IsMacroRulesItem
::Yes { has_bang }
= self.is_macro_rules_item() {
290 self.parse_item_macro_rules(vis
, has_bang
)?
291 } else if vis
.kind
.is_pub() && self.isnt_macro_invocation() {
292 self.recover_missing_kw_before_item()?
;
294 } else if macros_allowed
&& self.check_path() {
295 // MACRO INVOCATION ITEM
296 (Ident
::empty(), ItemKind
::MacCall(self.parse_item_macro(vis
)?
))
303 /// When parsing a statement, would the start of a path be an item?
304 pub(super) fn is_path_start_item(&mut self) -> bool
{
305 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
306 || self.is_kw_followed_by_ident(kw
::Union
) // no: `union::b`, yes: `union U { .. }`
307 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
308 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
309 || matches
!(self.is_macro_rules_item(), IsMacroRulesItem
::Yes{..}
) // no: `macro_rules::b`, yes: `macro_rules! mac`
312 /// Are we sure this could not possibly be a macro invocation?
313 fn isnt_macro_invocation(&mut self) -> bool
{
314 self.check_ident() && self.look_ahead(1, |t
| *t
!= token
::Not
&& *t
!= token
::ModSep
)
317 /// Recover on encountering a struct or method definition where the user
318 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
319 fn recover_missing_kw_before_item(&mut self) -> PResult
<'a
, ()> {
320 // Space between `pub` keyword and the identifier
323 // ^^^ `sp` points here
324 let sp
= self.prev_token
.span
.between(self.token
.span
);
325 let full_sp
= self.prev_token
.span
.to(self.token
.span
);
326 let ident_sp
= self.token
.span
;
327 if self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Brace
)) {
328 // possible public struct definition where `struct` was forgotten
329 let ident
= self.parse_ident().unwrap();
330 let msg
= format
!("add `struct` here to parse `{ident}` as a public struct");
331 let mut err
= self.struct_span_err(sp
, "missing `struct` for struct definition");
332 err
.span_suggestion_short(
336 Applicability
::MaybeIncorrect
, // speculative
339 } else if self.look_ahead(1, |t
| *t
== token
::OpenDelim(token
::Paren
)) {
340 let ident
= self.parse_ident().unwrap();
342 let kw_name
= self.recover_first_param();
343 self.consume_block(token
::Paren
, ConsumeClosingDelim
::Yes
);
344 let (kw
, kw_name
, ambiguous
) = if self.check(&token
::RArrow
) {
345 self.eat_to_tokens(&[&token
::OpenDelim(token
::Brace
)]);
347 ("fn", kw_name
, false)
348 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
350 ("fn", kw_name
, false)
351 } else if self.check(&token
::Colon
) {
355 ("fn` or `struct", "function or struct", true)
358 let msg
= format
!("missing `{kw}` for {kw_name} definition");
359 let mut err
= self.struct_span_err(sp
, &msg
);
361 self.consume_block(token
::Brace
, ConsumeClosingDelim
::Yes
);
363 format
!("add `{kw}` here to parse `{ident}` as a public {kw_name}");
364 err
.span_suggestion_short(
368 Applicability
::MachineApplicable
,
370 } else if let Ok(snippet
) = self.span_to_snippet(ident_sp
) {
373 "if you meant to call a macro, try",
374 format
!("{}!", snippet
),
375 // this is the `ambiguous` conditional branch
376 Applicability
::MaybeIncorrect
,
380 "if you meant to call a macro, remove the `pub` \
381 and add a trailing `!` after the identifier",
385 } else if self.look_ahead(1, |t
| *t
== token
::Lt
) {
386 let ident
= self.parse_ident().unwrap();
387 self.eat_to_tokens(&[&token
::Gt
]);
389 let (kw
, kw_name
, ambiguous
) = if self.eat(&token
::OpenDelim(token
::Paren
)) {
390 ("fn", self.recover_first_param(), false)
391 } else if self.check(&token
::OpenDelim(token
::Brace
)) {
392 ("struct", "struct", false)
394 ("fn` or `struct", "function or struct", true)
396 let msg
= format
!("missing `{kw}` for {kw_name} definition");
397 let mut err
= self.struct_span_err(sp
, &msg
);
399 err
.span_suggestion_short(
401 &format
!("add `{kw}` here to parse `{ident}` as a public {kw_name}"),
403 Applicability
::MachineApplicable
,
412 /// Parses an item macro, e.g., `item!();`.
413 fn parse_item_macro(&mut self, vis
: &Visibility
) -> PResult
<'a
, MacCall
> {
414 let path
= self.parse_path(PathStyle
::Mod
)?
; // `foo::bar`
415 self.expect(&token
::Not
)?
; // `!`
416 match self.parse_mac_args() {
417 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
419 self.eat_semi_for_macro_if_needed(&args
);
420 self.complain_if_pub_macro(vis
, false);
421 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription }
)
425 // Maybe the user misspelled `macro_rules` (issue #91227)
426 if self.token
.is_ident()
427 && path
.segments
.len() == 1
428 && lev_distance("macro_rules", &path
.segments
[0].ident
.to_string(), 3).is_some()
432 "perhaps you meant to define a macro",
433 "macro_rules".to_string(),
434 Applicability
::MachineApplicable
,
442 /// Recover if we parsed attributes and expected an item but there was none.
443 fn recover_attrs_no_item(&mut self, attrs
: &[Attribute
]) -> PResult
<'a
, ()> {
444 let ([start @ end
] | [start
, .., end
]) = attrs
else {
447 let msg
= if end
.is_doc_comment() {
448 "expected item after doc comment"
450 "expected item after attributes"
452 let mut err
= self.struct_span_err(end
.span
, msg
);
453 if end
.is_doc_comment() {
454 err
.span_label(end
.span
, "this doc comment doesn't document anything");
456 if end
.meta_kind().is_some() {
457 if self.token
.kind
== TokenKind
::Semi
{
458 err
.span_suggestion_verbose(
460 "consider removing this semicolon",
462 Applicability
::MaybeIncorrect
,
466 if let [.., penultimate
, _
] = attrs
{
467 err
.span_label(start
.span
.to(penultimate
.span
), "other attributes here");
472 fn is_async_fn(&self) -> bool
{
473 self.token
.is_keyword(kw
::Async
) && self.is_keyword_ahead(1, &[kw
::Fn
])
476 fn parse_polarity(&mut self) -> ast
::ImplPolarity
{
477 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
478 if self.check(&token
::Not
) && self.look_ahead(1, |t
| t
.can_begin_type()) {
480 ast
::ImplPolarity
::Negative(self.prev_token
.span
)
482 ast
::ImplPolarity
::Positive
486 /// Parses an implementation item.
489 /// impl<'a, T> TYPE { /* impl items */ }
490 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
491 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
492 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
495 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
497 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
498 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
502 attrs
: &mut Vec
<Attribute
>,
503 defaultness
: Defaultness
,
504 ) -> PResult
<'a
, ItemInfo
> {
505 let unsafety
= self.parse_unsafety();
506 self.expect_keyword(kw
::Impl
)?
;
508 // First, parse generic parameters if necessary.
509 let mut generics
= if self.choose_generics_over_qpath(0) {
510 self.parse_generics()?
512 let mut generics
= Generics
::default();
514 // /\ this is where `generics.span` should point when there are no type params.
515 generics
.span
= self.prev_token
.span
.shrink_to_hi();
519 let constness
= self.parse_constness();
520 if let Const
::Yes(span
) = constness
{
521 self.sess
.gated_spans
.gate(sym
::const_trait_impl
, span
);
524 let polarity
= self.parse_polarity();
526 // Parse both types and traits as a type, then reinterpret if necessary.
527 let err_path
= |span
| ast
::Path
::from_ident(Ident
::new(kw
::Empty
, span
));
528 let ty_first
= if self.token
.is_keyword(kw
::For
) && self.look_ahead(1, |t
| t
!= &token
::Lt
)
530 let span
= self.prev_token
.span
.between(self.token
.span
);
531 self.struct_span_err(span
, "missing trait in a trait impl")
536 Applicability
::HasPlaceholders
,
539 span
.to(self.token
.span
),
540 "for an inherent impl, drop this `for`",
542 Applicability
::MaybeIncorrect
,
546 kind
: TyKind
::Path(None
, err_path(span
)),
552 self.parse_ty_with_generics_recovery(&generics
)?
555 // If `for` is missing we try to recover.
556 let has_for
= self.eat_keyword(kw
::For
);
557 let missing_for_span
= self.prev_token
.span
.between(self.token
.span
);
559 let ty_second
= if self.token
== token
::DotDot
{
560 // We need to report this error after `cfg` expansion for compatibility reasons
561 self.bump(); // `..`, do not add it to expected tokens
562 Some(self.mk_ty(self.prev_token
.span
, TyKind
::Err
))
563 } else if has_for
|| self.token
.can_begin_type() {
564 Some(self.parse_ty()?
)
569 generics
.where_clause
= self.parse_where_clause()?
;
571 let impl_items
= self.parse_item_list(attrs
, |p
| p
.parse_impl_item(ForceCollect
::No
))?
;
573 let item_kind
= match ty_second
{
575 // impl Trait for Type
577 self.struct_span_err(missing_for_span
, "missing `for` in a trait impl")
578 .span_suggestion_short(
582 Applicability
::MachineApplicable
,
587 let ty_first
= ty_first
.into_inner();
588 let path
= match ty_first
.kind
{
589 // This notably includes paths passed through `ty` macro fragments (#46438).
590 TyKind
::Path(None
, path
) => path
,
592 self.struct_span_err(ty_first
.span
, "expected a trait, found type").emit();
593 err_path(ty_first
.span
)
596 let trait_ref
= TraitRef { path, ref_id: ty_first.id }
;
598 ItemKind
::Impl(Box
::new(Impl
{
604 of_trait
: Some(trait_ref
),
611 ItemKind
::Impl(Box
::new(Impl
{
624 Ok((Ident
::empty(), item_kind
))
627 fn parse_item_list
<T
>(
629 attrs
: &mut Vec
<Attribute
>,
630 mut parse_item
: impl FnMut(&mut Parser
<'a
>) -> PResult
<'a
, Option
<Option
<T
>>>,
631 ) -> PResult
<'a
, Vec
<T
>> {
632 let open_brace_span
= self.token
.span
;
633 self.expect(&token
::OpenDelim(token
::Brace
))?
;
634 attrs
.append(&mut self.parse_inner_attributes()?
);
636 let mut items
= Vec
::new();
637 while !self.eat(&token
::CloseDelim(token
::Brace
)) {
638 if self.recover_doc_comment_before_brace() {
641 match parse_item(self) {
643 // We have to bail or we'll potentially never make progress.
644 let non_item_span
= self.token
.span
;
645 self.consume_block(token
::Brace
, ConsumeClosingDelim
::Yes
);
646 self.struct_span_err(non_item_span
, "non-item in item list")
647 .span_label(open_brace_span
, "item list starts here")
648 .span_label(non_item_span
, "non-item starts here")
649 .span_label(self.prev_token
.span
, "item list ends here")
653 Ok(Some(item
)) => items
.extend(item
),
655 self.consume_block(token
::Brace
, ConsumeClosingDelim
::Yes
);
656 err
.span_label(open_brace_span
, "while parsing this item list starting here")
657 .span_label(self.prev_token
.span
, "the item list ends here")
666 /// Recover on a doc comment before `}`.
667 fn recover_doc_comment_before_brace(&mut self) -> bool
{
668 if let token
::DocComment(..) = self.token
.kind
{
669 if self.look_ahead(1, |tok
| tok
== &token
::CloseDelim(token
::Brace
)) {
674 "found a documentation comment that doesn't document anything",
676 .span_label(self.token
.span
, "this doc comment doesn't document anything")
678 "doc comments must come before what they document, maybe a \
679 comment was intended with `//`?",
689 /// Parses defaultness (i.e., `default` or nothing).
690 fn parse_defaultness(&mut self) -> Defaultness
{
691 // We are interested in `default` followed by another identifier.
692 // However, we must avoid keywords that occur as binary operators.
693 // Currently, the only applicable keyword is `as` (`default as Ty`).
694 if self.check_keyword(kw
::Default
)
695 && self.look_ahead(1, |t
| t
.is_non_raw_ident_where(|i
| i
.name
!= kw
::As
))
697 self.bump(); // `default`
698 Defaultness
::Default(self.prev_token
.uninterpolated_span())
704 /// Is this an `(unsafe auto? | auto) trait` item?
705 fn check_auto_or_unsafe_trait_item(&mut self) -> bool
{
707 self.check_keyword(kw
::Auto
) && self.is_keyword_ahead(1, &[kw
::Trait
])
709 || self.check_keyword(kw
::Unsafe
) && self.is_keyword_ahead(1, &[kw
::Trait
, kw
::Auto
])
712 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
713 fn parse_item_trait(&mut self, attrs
: &mut Vec
<Attribute
>, lo
: Span
) -> PResult
<'a
, ItemInfo
> {
714 let unsafety
= self.parse_unsafety();
715 // Parse optional `auto` prefix.
716 let is_auto
= if self.eat_keyword(kw
::Auto
) { IsAuto::Yes }
else { IsAuto::No }
;
718 self.expect_keyword(kw
::Trait
)?
;
719 let ident
= self.parse_ident()?
;
720 let mut generics
= self.parse_generics()?
;
722 // Parse optional colon and supertrait bounds.
723 let had_colon
= self.eat(&token
::Colon
);
724 let span_at_colon
= self.prev_token
.span
;
725 let bounds
= if had_colon
{
726 self.parse_generic_bounds(Some(self.prev_token
.span
))?
731 let span_before_eq
= self.prev_token
.span
;
732 if self.eat(&token
::Eq
) {
733 // It's a trait alias.
735 let span
= span_at_colon
.to(span_before_eq
);
736 self.struct_span_err(span
, "bounds are not allowed on trait aliases").emit();
739 let bounds
= self.parse_generic_bounds(None
)?
;
740 generics
.where_clause
= self.parse_where_clause()?
;
743 let whole_span
= lo
.to(self.prev_token
.span
);
744 if is_auto
== IsAuto
::Yes
{
745 let msg
= "trait aliases cannot be `auto`";
746 self.struct_span_err(whole_span
, msg
).span_label(whole_span
, msg
).emit();
748 if let Unsafe
::Yes(_
) = unsafety
{
749 let msg
= "trait aliases cannot be `unsafe`";
750 self.struct_span_err(whole_span
, msg
).span_label(whole_span
, msg
).emit();
753 self.sess
.gated_spans
.gate(sym
::trait_alias
, whole_span
);
755 Ok((ident
, ItemKind
::TraitAlias(generics
, bounds
)))
757 // It's a normal trait.
758 generics
.where_clause
= self.parse_where_clause()?
;
759 let items
= self.parse_item_list(attrs
, |p
| p
.parse_trait_item(ForceCollect
::No
))?
;
762 ItemKind
::Trait(Box
::new(Trait { is_auto, unsafety, generics, bounds, items }
)),
767 pub fn parse_impl_item(
769 force_collect
: ForceCollect
,
770 ) -> PResult
<'a
, Option
<Option
<P
<AssocItem
>>>> {
771 let fn_parse_mode
= FnParseMode { req_name: |_| true, req_body: true }
;
772 self.parse_assoc_item(fn_parse_mode
, force_collect
)
775 pub fn parse_trait_item(
777 force_collect
: ForceCollect
,
778 ) -> PResult
<'a
, Option
<Option
<P
<AssocItem
>>>> {
780 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false }
;
781 self.parse_assoc_item(fn_parse_mode
, force_collect
)
784 /// Parses associated items.
787 fn_parse_mode
: FnParseMode
,
788 force_collect
: ForceCollect
,
789 ) -> PResult
<'a
, Option
<Option
<P
<AssocItem
>>>> {
790 Ok(self.parse_item_(fn_parse_mode
, force_collect
)?
.map(
791 |Item { attrs, id, span, vis, ident, kind, tokens }
| {
792 let kind
= match AssocItemKind
::try_from(kind
) {
794 Err(kind
) => match kind
{
795 ItemKind
::Static(a
, _
, b
) => {
796 self.struct_span_err(span
, "associated `static` items are not allowed")
798 AssocItemKind
::Const(Defaultness
::Final
, a
, b
)
800 _
=> return self.error_bad_item_kind(span
, &kind
, "`trait`s or `impl`s"),
803 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }
))
808 /// Parses a `type` alias with the following grammar:
810 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
812 /// The `"type"` has already been eaten.
813 fn parse_type_alias(&mut self, defaultness
: Defaultness
) -> PResult
<'a
, ItemInfo
> {
814 let ident
= self.parse_ident()?
;
815 let mut generics
= self.parse_generics()?
;
817 // Parse optional colon and param bounds.
819 if self.eat(&token
::Colon
) { self.parse_generic_bounds(None)? }
else { Vec::new() }
;
820 let before_where_clause
= self.parse_where_clause()?
;
822 let ty
= if self.eat(&token
::Eq
) { Some(self.parse_ty()?) }
else { None }
;
824 let after_where_clause
= self.parse_where_clause()?
;
826 let where_clauses
= (
827 TyAliasWhereClause(before_where_clause
.has_where_token
, before_where_clause
.span
),
828 TyAliasWhereClause(after_where_clause
.has_where_token
, after_where_clause
.span
),
830 let where_predicates_split
= before_where_clause
.predicates
.len();
831 let mut predicates
= before_where_clause
.predicates
;
832 predicates
.extend(after_where_clause
.predicates
.into_iter());
833 let where_clause
= WhereClause
{
834 has_where_token
: before_where_clause
.has_where_token
835 || after_where_clause
.has_where_token
,
839 generics
.where_clause
= where_clause
;
845 ItemKind
::TyAlias(Box
::new(TyAlias
{
849 where_predicates_split
,
856 /// Parses a `UseTree`.
859 /// USE_TREE = [`::`] `*` |
860 /// [`::`] `{` USE_TREE_LIST `}` |
862 /// PATH `::` `{` USE_TREE_LIST `}` |
863 /// PATH [`as` IDENT]
865 fn parse_use_tree(&mut self) -> PResult
<'a
, UseTree
> {
866 let lo
= self.token
.span
;
868 let mut prefix
= ast
::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None }
;
869 let kind
= if self.check(&token
::OpenDelim(token
::Brace
))
870 || self.check(&token
::BinOp(token
::Star
))
871 || self.is_import_coupler()
873 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
874 let mod_sep_ctxt
= self.token
.span
.ctxt();
875 if self.eat(&token
::ModSep
) {
878 .push(PathSegment
::path_root(lo
.shrink_to_lo().with_ctxt(mod_sep_ctxt
)));
881 self.parse_use_tree_glob_or_nested()?
883 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
884 prefix
= self.parse_path(PathStyle
::Mod
)?
;
886 if self.eat(&token
::ModSep
) {
887 self.parse_use_tree_glob_or_nested()?
889 UseTreeKind
::Simple(self.parse_rename()?
, DUMMY_NODE_ID
, DUMMY_NODE_ID
)
893 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) }
)
896 /// Parses `*` or `{...}`.
897 fn parse_use_tree_glob_or_nested(&mut self) -> PResult
<'a
, UseTreeKind
> {
898 Ok(if self.eat(&token
::BinOp(token
::Star
)) {
901 UseTreeKind
::Nested(self.parse_use_tree_list()?
)
905 /// Parses a `UseTreeKind::Nested(list)`.
908 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
910 fn parse_use_tree_list(&mut self) -> PResult
<'a
, Vec
<(UseTree
, ast
::NodeId
)>> {
911 self.parse_delim_comma_seq(token
::Brace
, |p
| Ok((p
.parse_use_tree()?
, DUMMY_NODE_ID
)))
915 fn parse_rename(&mut self) -> PResult
<'a
, Option
<Ident
>> {
916 if self.eat_keyword(kw
::As
) { self.parse_ident_or_underscore().map(Some) }
else { Ok(None) }
919 fn parse_ident_or_underscore(&mut self) -> PResult
<'a
, Ident
> {
920 match self.token
.ident() {
921 Some((ident @ Ident { name: kw::Underscore, .. }
, false)) => {
925 _
=> self.parse_ident(),
929 /// Parses `extern crate` links.
934 /// extern crate foo;
935 /// extern crate bar as foo;
937 fn parse_item_extern_crate(&mut self) -> PResult
<'a
, ItemInfo
> {
938 // Accept `extern crate name-like-this` for better diagnostics
939 let orig_name
= self.parse_crate_name_with_dashes()?
;
940 let (item_name
, orig_name
) = if let Some(rename
) = self.parse_rename()?
{
941 (rename
, Some(orig_name
.name
))
946 Ok((item_name
, ItemKind
::ExternCrate(orig_name
)))
949 fn parse_crate_name_with_dashes(&mut self) -> PResult
<'a
, Ident
> {
950 let error_msg
= "crate name using dashes are not valid in `extern crate` statements";
951 let suggestion_msg
= "if the original crate name uses dashes you need to use underscores \
953 let mut ident
= if self.token
.is_keyword(kw
::SelfLower
) {
954 self.parse_path_segment_ident()
958 let mut idents
= vec
![];
959 let mut replacement
= vec
![];
960 let mut fixed_crate_name
= false;
961 // Accept `extern crate name-like-this` for better diagnostics.
962 let dash
= token
::BinOp(token
::BinOpToken
::Minus
);
963 if self.token
== dash
{
964 // Do not include `-` as part of the expected tokens list.
965 while self.eat(&dash
) {
966 fixed_crate_name
= true;
967 replacement
.push((self.prev_token
.span
, "_".to_string()));
968 idents
.push(self.parse_ident()?
);
971 if fixed_crate_name
{
972 let fixed_name_sp
= ident
.span
.to(idents
.last().unwrap().span
);
973 let mut fixed_name
= format
!("{}", ident
.name
);
975 fixed_name
.push_str(&format
!("_{}", part
.name
));
977 ident
= Ident
::from_str_and_span(&fixed_name
, fixed_name_sp
);
979 self.struct_span_err(fixed_name_sp
, error_msg
)
980 .span_label(fixed_name_sp
, "dash-separated idents are not valid")
981 .multipart_suggestion(suggestion_msg
, replacement
, Applicability
::MachineApplicable
)
987 /// Parses `extern` for foreign ABIs modules.
989 /// `extern` is expected to have been consumed before calling this method.
993 /// ```ignore (only-for-syntax-highlight)
997 fn parse_item_foreign_mod(
999 attrs
: &mut Vec
<Attribute
>,
1001 ) -> PResult
<'a
, ItemInfo
> {
1002 let sp_start
= self.prev_token
.span
;
1003 let abi
= self.parse_abi(); // ABI?
1004 match self.parse_item_list(attrs
, |p
| p
.parse_foreign_item(ForceCollect
::No
)) {
1006 let module
= ast
::ForeignMod { unsafety, abi, items }
;
1007 Ok((Ident
::empty(), ItemKind
::ForeignMod(module
)))
1010 let current_qual_sp
= self.prev_token
.span
;
1011 let current_qual_sp
= current_qual_sp
.to(sp_start
);
1012 if let Ok(current_qual
) = self.span_to_snippet(current_qual_sp
) {
1013 if err
.message() == "expected `{`, found keyword `unsafe`" {
1014 let invalid_qual_sp
= self.token
.uninterpolated_span();
1015 let invalid_qual
= self.span_to_snippet(invalid_qual_sp
).unwrap();
1017 err
.span_suggestion(
1018 current_qual_sp
.to(invalid_qual_sp
),
1019 &format
!("`{}` must come before `{}`", invalid_qual
, current_qual
),
1020 format
!("{} {}", invalid_qual
, current_qual
),
1021 Applicability
::MachineApplicable
,
1022 ).note("keyword order for functions declaration is `default`, `pub`, `const`, `async`, `unsafe`, `extern`");
1030 /// Parses a foreign item (one in an `extern { ... }` block).
1031 pub fn parse_foreign_item(
1033 force_collect
: ForceCollect
,
1034 ) -> PResult
<'a
, Option
<Option
<P
<ForeignItem
>>>> {
1035 let fn_parse_mode
= FnParseMode { req_name: |_| true, req_body: false }
;
1036 Ok(self.parse_item_(fn_parse_mode
, force_collect
)?
.map(
1037 |Item { attrs, id, span, vis, ident, kind, tokens }
| {
1038 let kind
= match ForeignItemKind
::try_from(kind
) {
1040 Err(kind
) => match kind
{
1041 ItemKind
::Const(_
, a
, b
) => {
1042 self.error_on_foreign_const(span
, ident
);
1043 ForeignItemKind
::Static(a
, Mutability
::Not
, b
)
1045 _
=> return self.error_bad_item_kind(span
, &kind
, "`extern` blocks"),
1048 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }
))
1053 fn error_bad_item_kind
<T
>(&self, span
: Span
, kind
: &ItemKind
, ctx
: &str) -> Option
<T
> {
1054 let span
= self.sess
.source_map().guess_head_span(span
);
1055 let descr
= kind
.descr();
1056 self.struct_span_err(span
, &format
!("{descr} is not supported in {ctx}"))
1057 .help(&format
!("consider moving the {descr} out to a nearby module scope"))
1062 fn error_on_foreign_const(&self, span
: Span
, ident
: Ident
) {
1063 self.struct_span_err(ident
.span
, "extern items cannot be `const`")
1065 span
.with_hi(ident
.span
.lo()),
1066 "try using a static value",
1067 "static ".to_string(),
1068 Applicability
::MachineApplicable
,
1070 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1074 fn is_unsafe_foreign_mod(&self) -> bool
{
1075 self.token
.is_keyword(kw
::Unsafe
)
1076 && self.is_keyword_ahead(1, &[kw
::Extern
])
1078 2 + self.look_ahead(2, |t
| t
.can_begin_literal_maybe_minus() as usize),
1079 |t
| t
.kind
== token
::OpenDelim(token
::Brace
),
1083 fn is_static_global(&mut self) -> bool
{
1084 if self.check_keyword(kw
::Static
) {
1085 // Check if this could be a closure.
1086 !self.look_ahead(1, |token
| {
1087 if token
.is_keyword(kw
::Move
) {
1090 matches
!(token
.kind
, token
::BinOp(token
::Or
) | token
::OrOr
)
1097 /// Recover on `const mut` with `const` already eaten.
1098 fn recover_const_mut(&mut self, const_span
: Span
) {
1099 if self.eat_keyword(kw
::Mut
) {
1100 let span
= self.prev_token
.span
;
1101 self.struct_span_err(span
, "const globals cannot be mutable")
1102 .span_label(span
, "cannot be mutable")
1105 "you might want to declare a static instead",
1106 "static".to_owned(),
1107 Applicability
::MaybeIncorrect
,
1113 /// Recover on `const impl` with `const` already eaten.
1114 fn recover_const_impl(
1117 attrs
: &mut Vec
<Attribute
>,
1118 defaultness
: Defaultness
,
1119 ) -> PResult
<'a
, ItemInfo
> {
1120 let impl_span
= self.token
.span
;
1121 let mut err
= self.expected_ident_found();
1123 // Only try to recover if this is implementing a trait for a type
1124 let mut impl_info
= match self.parse_item_impl(attrs
, defaultness
) {
1125 Ok(impl_info
) => impl_info
,
1126 Err(recovery_error
) => {
1127 // Recovery failed, raise the "expected identifier" error
1128 recovery_error
.cancel();
1134 ItemKind
::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }
) => {
1135 *constness
= Const
::Yes(const_span
);
1137 let before_trait
= trai
.path
.span
.shrink_to_lo();
1138 let const_up_to_impl
= const_span
.with_hi(impl_span
.lo());
1139 err
.multipart_suggestion(
1140 "you might have meant to write a const trait impl",
1141 vec
![(const_up_to_impl
, "".to_owned()), (before_trait
, "const ".to_owned())],
1142 Applicability
::MaybeIncorrect
,
1146 ItemKind
::Impl { .. }
=> return Err(err
),
1147 _
=> unreachable
!(),
1153 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1154 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1156 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1157 fn parse_item_global(
1159 m
: Option
<Mutability
>,
1160 ) -> PResult
<'a
, (Ident
, P
<Ty
>, Option
<P
<ast
::Expr
>>)> {
1161 let id
= if m
.is_none() { self.parse_ident_or_underscore() }
else { self.parse_ident() }?
;
1163 // Parse the type of a `const` or `static mut?` item.
1164 // That is, the `":" $ty` fragment.
1165 let ty
= if self.eat(&token
::Colon
) {
1168 self.recover_missing_const_type(id
, m
)
1171 let expr
= if self.eat(&token
::Eq
) { Some(self.parse_expr()?) }
else { None }
;
1172 self.expect_semi()?
;
1176 /// We were supposed to parse `:` but the `:` was missing.
1177 /// This means that the type is missing.
1178 fn recover_missing_const_type(&mut self, id
: Ident
, m
: Option
<Mutability
>) -> P
<Ty
> {
1179 // Construct the error and stash it away with the hope
1180 // that typeck will later enrich the error with a type.
1181 let kind
= match m
{
1182 Some(Mutability
::Mut
) => "static mut",
1183 Some(Mutability
::Not
) => "static",
1186 let mut err
= self.struct_span_err(id
.span
, &format
!("missing type for `{kind}` item"));
1187 err
.span_suggestion(
1189 "provide a type for the item",
1190 format
!("{id}: <type>"),
1191 Applicability
::HasPlaceholders
,
1193 err
.stash(id
.span
, StashKey
::ItemNoType
);
1195 // The user intended that the type be inferred,
1196 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1197 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None }
)
1200 /// Parses an enum declaration.
1201 fn parse_item_enum(&mut self) -> PResult
<'a
, ItemInfo
> {
1202 let id
= self.parse_ident()?
;
1203 let mut generics
= self.parse_generics()?
;
1204 generics
.where_clause
= self.parse_where_clause()?
;
1207 self.parse_delim_comma_seq(token
::Brace
, |p
| p
.parse_enum_variant()).map_err(|e
| {
1208 self.recover_stmt();
1212 let enum_definition
= EnumDef { variants: variants.into_iter().flatten().collect() }
;
1213 Ok((id
, ItemKind
::Enum(enum_definition
, generics
)))
1216 fn parse_enum_variant(&mut self) -> PResult
<'a
, Option
<Variant
>> {
1217 let variant_attrs
= self.parse_outer_attributes()?
;
1218 self.collect_tokens_trailing_token(
1221 |this
, variant_attrs
| {
1222 let vlo
= this
.token
.span
;
1224 let vis
= this
.parse_visibility(FollowedByType
::No
)?
;
1225 if !this
.recover_nested_adt_item(kw
::Enum
)?
{
1226 return Ok((None
, TrailingToken
::None
));
1228 let ident
= this
.parse_field_ident("enum", vlo
)?
;
1230 let struct_def
= if this
.check(&token
::OpenDelim(token
::Brace
)) {
1231 // Parse a struct variant.
1232 let (fields
, recovered
) = this
.parse_record_struct_body("struct", false)?
;
1233 VariantData
::Struct(fields
, recovered
)
1234 } else if this
.check(&token
::OpenDelim(token
::Paren
)) {
1235 VariantData
::Tuple(this
.parse_tuple_struct_body()?
, DUMMY_NODE_ID
)
1237 VariantData
::Unit(DUMMY_NODE_ID
)
1241 if this
.eat(&token
::Eq
) { Some(this.parse_anon_const_expr()?) }
else { None }
;
1243 let vr
= ast
::Variant
{
1247 attrs
: variant_attrs
.into(),
1250 span
: vlo
.to(this
.prev_token
.span
),
1251 is_placeholder
: false,
1254 Ok((Some(vr
), TrailingToken
::MaybeComma
))
1259 /// Parses `struct Foo { ... }`.
1260 fn parse_item_struct(&mut self) -> PResult
<'a
, ItemInfo
> {
1261 let class_name
= self.parse_ident()?
;
1263 let mut generics
= self.parse_generics()?
;
1265 // There is a special case worth noting here, as reported in issue #17904.
1266 // If we are parsing a tuple struct it is the case that the where clause
1267 // should follow the field list. Like so:
1269 // struct Foo<T>(T) where T: Copy;
1271 // If we are parsing a normal record-style struct it is the case
1272 // that the where clause comes before the body, and after the generics.
1273 // So if we look ahead and see a brace or a where-clause we begin
1274 // parsing a record style struct.
1276 // Otherwise if we look ahead and see a paren we parse a tuple-style
1279 let vdata
= if self.token
.is_keyword(kw
::Where
) {
1280 generics
.where_clause
= self.parse_where_clause()?
;
1281 if self.eat(&token
::Semi
) {
1282 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1283 VariantData
::Unit(DUMMY_NODE_ID
)
1285 // If we see: `struct Foo<T> where T: Copy { ... }`
1286 let (fields
, recovered
) =
1287 self.parse_record_struct_body("struct", generics
.where_clause
.has_where_token
)?
;
1288 VariantData
::Struct(fields
, recovered
)
1290 // No `where` so: `struct Foo<T>;`
1291 } else if self.eat(&token
::Semi
) {
1292 VariantData
::Unit(DUMMY_NODE_ID
)
1293 // Record-style struct definition
1294 } else if self.token
== token
::OpenDelim(token
::Brace
) {
1295 let (fields
, recovered
) =
1296 self.parse_record_struct_body("struct", generics
.where_clause
.has_where_token
)?
;
1297 VariantData
::Struct(fields
, recovered
)
1298 // Tuple-style struct definition with optional where-clause.
1299 } else if self.token
== token
::OpenDelim(token
::Paren
) {
1300 let body
= VariantData
::Tuple(self.parse_tuple_struct_body()?
, DUMMY_NODE_ID
);
1301 generics
.where_clause
= self.parse_where_clause()?
;
1302 self.expect_semi()?
;
1305 let token_str
= super::token_descr(&self.token
);
1307 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1309 let mut err
= self.struct_span_err(self.token
.span
, msg
);
1310 err
.span_label(self.token
.span
, "expected `where`, `{`, `(`, or `;` after struct name");
1314 Ok((class_name
, ItemKind
::Struct(vdata
, generics
)))
1317 /// Parses `union Foo { ... }`.
1318 fn parse_item_union(&mut self) -> PResult
<'a
, ItemInfo
> {
1319 let class_name
= self.parse_ident()?
;
1321 let mut generics
= self.parse_generics()?
;
1323 let vdata
= if self.token
.is_keyword(kw
::Where
) {
1324 generics
.where_clause
= self.parse_where_clause()?
;
1325 let (fields
, recovered
) =
1326 self.parse_record_struct_body("union", generics
.where_clause
.has_where_token
)?
;
1327 VariantData
::Struct(fields
, recovered
)
1328 } else if self.token
== token
::OpenDelim(token
::Brace
) {
1329 let (fields
, recovered
) =
1330 self.parse_record_struct_body("union", generics
.where_clause
.has_where_token
)?
;
1331 VariantData
::Struct(fields
, recovered
)
1333 let token_str
= super::token_descr(&self.token
);
1334 let msg
= &format
!("expected `where` or `{{` after union name, found {token_str}");
1335 let mut err
= self.struct_span_err(self.token
.span
, msg
);
1336 err
.span_label(self.token
.span
, "expected `where` or `{` after union name");
1340 Ok((class_name
, ItemKind
::Union(vdata
, generics
)))
1343 fn parse_record_struct_body(
1347 ) -> PResult
<'a
, (Vec
<FieldDef
>, /* recovered */ bool
)> {
1348 let mut fields
= Vec
::new();
1349 let mut recovered
= false;
1350 if self.eat(&token
::OpenDelim(token
::Brace
)) {
1351 while self.token
!= token
::CloseDelim(token
::Brace
) {
1352 let field
= self.parse_field_def(adt_ty
).map_err(|e
| {
1353 self.consume_block(token
::Brace
, ConsumeClosingDelim
::No
);
1358 Ok(field
) => fields
.push(field
),
1365 self.eat(&token
::CloseDelim(token
::Brace
));
1367 let token_str
= super::token_descr(&self.token
);
1369 "expected {}`{{` after struct name, found {}",
1370 if parsed_where { "" }
else { "`where`, or " }
,
1373 let mut err
= self.struct_span_err(self.token
.span
, msg
);
1377 "expected {}`{{` after struct name",
1378 if parsed_where { "" }
else { "`where`, or " }
1384 Ok((fields
, recovered
))
1387 fn parse_tuple_struct_body(&mut self) -> PResult
<'a
, Vec
<FieldDef
>> {
1388 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1389 // Unit like structs are handled in parse_item_struct function
1390 self.parse_paren_comma_seq(|p
| {
1391 let attrs
= p
.parse_outer_attributes()?
;
1392 p
.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |p
, attrs
| {
1393 let lo
= p
.token
.span
;
1394 let vis
= p
.parse_visibility(FollowedByType
::Yes
)?
;
1395 let ty
= p
.parse_ty()?
;
1399 span
: lo
.to(ty
.span
),
1404 attrs
: attrs
.into(),
1405 is_placeholder
: false,
1407 TrailingToken
::MaybeComma
,
1414 /// Parses an element of a struct declaration.
1415 fn parse_field_def(&mut self, adt_ty
: &str) -> PResult
<'a
, FieldDef
> {
1416 let attrs
= self.parse_outer_attributes()?
;
1417 self.collect_tokens_trailing_token(attrs
, ForceCollect
::No
, |this
, attrs
| {
1418 let lo
= this
.token
.span
;
1419 let vis
= this
.parse_visibility(FollowedByType
::No
)?
;
1420 Ok((this
.parse_single_struct_field(adt_ty
, lo
, vis
, attrs
)?
, TrailingToken
::None
))
1424 /// Parses a structure field declaration.
1425 fn parse_single_struct_field(
1430 attrs
: Vec
<Attribute
>,
1431 ) -> PResult
<'a
, FieldDef
> {
1432 let mut seen_comma
: bool
= false;
1433 let a_var
= self.parse_name_and_ty(adt_ty
, lo
, vis
, attrs
)?
;
1434 if self.token
== token
::Comma
{
1437 match self.token
.kind
{
1441 token
::CloseDelim(token
::Brace
) => {}
1442 token
::DocComment(..) => {
1443 let previous_span
= self.prev_token
.span
;
1444 let mut err
= self.span_err(self.token
.span
, Error
::UselessDocComment
);
1445 self.bump(); // consume the doc comment
1446 let comma_after_doc_seen
= self.eat(&token
::Comma
);
1447 // `seen_comma` is always false, because we are inside doc block
1448 // condition is here to make code more readable
1449 if !seen_comma
&& comma_after_doc_seen
{
1452 if comma_after_doc_seen
|| self.token
== token
::CloseDelim(token
::Brace
) {
1456 let sp
= self.sess
.source_map().next_point(previous_span
);
1457 err
.span_suggestion(
1459 "missing comma here",
1461 Applicability
::MachineApplicable
,
1468 let sp
= self.prev_token
.span
.shrink_to_hi();
1469 let mut err
= self.struct_span_err(
1471 &format
!("expected `,`, or `}}`, found {}", super::token_descr(&self.token
)),
1474 // Try to recover extra trailing angle brackets
1475 let mut recovered
= false;
1476 if let TyKind
::Path(_
, Path { segments, .. }
) = &a_var
.ty
.kind
{
1477 if let Some(last_segment
) = segments
.last() {
1478 recovered
= self.check_trailing_angle_brackets(
1480 &[&token
::Comma
, &token
::CloseDelim(token
::Brace
)],
1483 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1485 self.eat(&token
::Comma
);
1486 // `check_trailing_angle_brackets` already emitted a nicer error
1487 // NOTE(eddyb) this was `.cancel()`, but `err`
1488 // gets returned, so we can't fully defuse it.
1494 if self.token
.is_ident() {
1495 // This is likely another field; emit the diagnostic and keep going
1496 err
.span_suggestion(
1498 "try adding a comma",
1500 Applicability
::MachineApplicable
,
1507 // Make sure an error was emitted (either by recovering an angle bracket,
1508 // or by finding an identifier as the next token), since we're
1509 // going to continue parsing
1510 assert
!(self.sess
.span_diagnostic
.has_errors().is_some());
1519 fn expect_field_ty_separator(&mut self) -> PResult
<'a
, ()> {
1520 if let Err(mut err
) = self.expect(&token
::Colon
) {
1521 let sm
= self.sess
.source_map();
1522 let eq_typo
= self.token
.kind
== token
::Eq
&& self.look_ahead(1, |t
| t
.is_path_start());
1523 let semi_typo
= self.token
.kind
== token
::Semi
1524 && self.look_ahead(1, |t
| {
1526 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1527 // when there's no type and `;` was used instead of a comma.
1528 && match (sm
.lookup_line(self.token
.span
.hi()), sm
.lookup_line(t
.span
.lo())) {
1529 (Ok(l
), Ok(r
)) => l
.line
== r
.line
,
1533 if eq_typo
|| semi_typo
{
1535 // Gracefully handle small typos.
1536 err
.span_suggestion_short(
1537 self.prev_token
.span
,
1538 "field names and their types are separated with `:`",
1540 Applicability
::MachineApplicable
,
1550 /// Parses a structure field.
1551 fn parse_name_and_ty(
1556 attrs
: Vec
<Attribute
>,
1557 ) -> PResult
<'a
, FieldDef
> {
1558 let name
= self.parse_field_ident(adt_ty
, lo
)?
;
1559 self.expect_field_ty_separator()?
;
1560 let ty
= self.parse_ty()?
;
1561 if self.token
.kind
== token
::Colon
&& self.look_ahead(1, |tok
| tok
.kind
!= token
::Colon
) {
1562 self.struct_span_err(self.token
.span
, "found single colon in a struct field type path")
1563 .span_suggestion_verbose(
1565 "write a path separator here",
1567 Applicability
::MaybeIncorrect
,
1571 if self.token
.kind
== token
::Eq
{
1573 let const_expr
= self.parse_anon_const_expr()?
;
1574 let sp
= ty
.span
.shrink_to_hi().to(const_expr
.value
.span
);
1575 self.struct_span_err(sp
, "default values on `struct` fields aren't supported")
1578 "remove this unsupported default value",
1580 Applicability
::MachineApplicable
,
1585 span
: lo
.to(self.prev_token
.span
),
1590 attrs
: attrs
.into(),
1591 is_placeholder
: false,
1595 /// Parses a field identifier. Specialized version of `parse_ident_common`
1596 /// for better diagnostics and suggestions.
1597 fn parse_field_ident(&mut self, adt_ty
: &str, lo
: Span
) -> PResult
<'a
, Ident
> {
1598 let (ident
, is_raw
) = self.ident_or_err()?
;
1599 if !is_raw
&& ident
.is_reserved() {
1600 let err
= if self.check_fn_front_matter(false) {
1601 let inherited_vis
= Visibility
{
1602 span
: rustc_span
::DUMMY_SP
,
1603 kind
: VisibilityKind
::Inherited
,
1606 // We use `parse_fn` to get a span for the function
1607 let fn_parse_mode
= FnParseMode { req_name: |_| true, req_body: true }
;
1608 if let Err(mut db
) =
1609 self.parse_fn(&mut Vec
::new(), fn_parse_mode
, lo
, &inherited_vis
)
1613 let mut err
= self.struct_span_err(
1614 lo
.to(self.prev_token
.span
),
1615 &format
!("functions are not allowed in {adt_ty} definitions"),
1617 err
.help("unlike in C++, Java, and C#, functions are declared in `impl` blocks");
1618 err
.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1621 self.expected_ident_found()
1629 /// Parses a declarative macro 2.0 definition.
1630 /// The `macro` keyword has already been parsed.
1632 /// MacBody = "{" TOKEN_STREAM "}" ;
1633 /// MacParams = "(" TOKEN_STREAM ")" ;
1634 /// DeclMac = "macro" Ident MacParams? MacBody ;
1636 fn parse_item_decl_macro(&mut self, lo
: Span
) -> PResult
<'a
, ItemInfo
> {
1637 let ident
= self.parse_ident()?
;
1638 let body
= if self.check(&token
::OpenDelim(token
::Brace
)) {
1639 self.parse_mac_args()?
// `MacBody`
1640 } else if self.check(&token
::OpenDelim(token
::Paren
)) {
1641 let params
= self.parse_token_tree(); // `MacParams`
1642 let pspan
= params
.span();
1643 if !self.check(&token
::OpenDelim(token
::Brace
)) {
1644 return self.unexpected();
1646 let body
= self.parse_token_tree(); // `MacBody`
1647 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1648 let bspan
= body
.span();
1649 let arrow
= TokenTree
::token(token
::FatArrow
, pspan
.between(bspan
)); // `=>`
1650 let tokens
= TokenStream
::new(vec
![params
.into(), arrow
.into(), body
.into()]);
1651 let dspan
= DelimSpan
::from_pair(pspan
.shrink_to_lo(), bspan
.shrink_to_hi());
1652 P(MacArgs
::Delimited(dspan
, MacDelimiter
::Brace
, tokens
))
1654 return self.unexpected();
1657 self.sess
.gated_spans
.gate(sym
::decl_macro
, lo
.to(self.prev_token
.span
));
1658 Ok((ident
, ItemKind
::MacroDef(ast
::MacroDef { body, macro_rules: false }
)))
1661 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1663 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem
{
1664 if self.check_keyword(kw
::MacroRules
) {
1665 let macro_rules_span
= self.token
.span
;
1667 if self.look_ahead(1, |t
| *t
== token
::Not
) && self.look_ahead(2, |t
| t
.is_ident()) {
1668 return IsMacroRulesItem
::Yes { has_bang: true }
;
1669 } else if self.look_ahead(1, |t
| (t
.is_ident())) {
1671 self.struct_span_err(macro_rules_span
, "expected `!` after `macro_rules`")
1675 "macro_rules!".to_owned(),
1676 Applicability
::MachineApplicable
,
1680 return IsMacroRulesItem
::Yes { has_bang: false }
;
1684 IsMacroRulesItem
::No
1687 /// Parses a `macro_rules! foo { ... }` declarative macro.
1688 fn parse_item_macro_rules(
1692 ) -> PResult
<'a
, ItemInfo
> {
1693 self.expect_keyword(kw
::MacroRules
)?
; // `macro_rules`
1696 self.expect(&token
::Not
)?
; // `!`
1698 let ident
= self.parse_ident()?
;
1700 if self.eat(&token
::Not
) {
1701 // Handle macro_rules! foo!
1702 let span
= self.prev_token
.span
;
1703 self.struct_span_err(span
, "macro names aren't followed by a `!`")
1708 Applicability
::MachineApplicable
,
1713 let body
= self.parse_mac_args()?
;
1714 self.eat_semi_for_macro_if_needed(&body
);
1715 self.complain_if_pub_macro(vis
, true);
1717 Ok((ident
, ItemKind
::MacroDef(ast
::MacroDef { body, macro_rules: true }
)))
1720 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1721 /// If that's not the case, emit an error.
1722 fn complain_if_pub_macro(&self, vis
: &Visibility
, macro_rules
: bool
) {
1723 if let VisibilityKind
::Inherited
= vis
.kind
{
1727 let vstr
= pprust
::vis_to_string(vis
);
1728 let vstr
= vstr
.trim_end();
1730 let msg
= format
!("can't qualify macro_rules invocation with `{vstr}`");
1731 self.struct_span_err(vis
.span
, &msg
)
1734 "try exporting the macro",
1735 "#[macro_export]".to_owned(),
1736 Applicability
::MaybeIncorrect
, // speculative
1740 self.struct_span_err(vis
.span
, "can't qualify macro invocation with `pub`")
1743 "remove the visibility",
1745 Applicability
::MachineApplicable
,
1747 .help(&format
!("try adjusting the macro to put `{vstr}` inside the invocation"))
1752 fn eat_semi_for_macro_if_needed(&mut self, args
: &MacArgs
) {
1753 if args
.need_semicolon() && !self.eat(&token
::Semi
) {
1754 self.report_invalid_macro_expansion_item(args
);
1758 fn report_invalid_macro_expansion_item(&self, args
: &MacArgs
) {
1759 let span
= args
.span().expect("undelimited macro call");
1760 let mut err
= self.struct_span_err(
1762 "macros that expand to items must be delimited with braces or followed by a semicolon",
1764 if self.unclosed_delims
.is_empty() {
1765 let DelimSpan { open, close }
= match args
{
1766 MacArgs
::Empty
| MacArgs
::Eq(..) => unreachable
!(),
1767 MacArgs
::Delimited(dspan
, ..) => *dspan
,
1769 err
.multipart_suggestion(
1770 "change the delimiters to curly braces",
1771 vec
![(open
, "{".to_string()), (close, '}'.to_string())],
1772 Applicability::MaybeIncorrect,
1775 err.span_suggestion(
1777 "change the delimiters to curly braces
",
1778 " { /* items */ }
".to_string(),
1779 Applicability::HasPlaceholders,
1782 err.span_suggestion(
1783 span.shrink_to_hi(),
1786 Applicability::MaybeIncorrect,
1791 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1792 /// it is, we try to parse the item and report error about nested types.
1793 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1794 if (self.token.is_keyword(kw::Enum)
1795 || self.token.is_keyword(kw::Struct)
1796 || self.token.is_keyword(kw::Union))
1797 && self.look_ahead(1, |t| t.is_ident())
1799 let kw_token = self.token.clone();
1800 let kw_str = pprust::token_to_string(&kw_token);
1801 let item = self.parse_item(ForceCollect::No)?;
1803 self.struct_span_err(
1805 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`
"),
1809 &format!("consider creating a new `{kw_str}` definition instead of nesting
"),
1811 Applicability::MaybeIncorrect,
1814 // We successfully parsed the item but we must inform the caller about nested problem.
1821 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1823 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1825 /// This function pointer accepts an edition, because in edition 2015, trait declarations
1826 /// were allowed to omit parameter names. In 2018, they became required.
1827 type ReqName = fn(Edition) -> bool;
1829 /// Parsing configuration for functions.
1831 /// The syntax of function items is slightly different within trait definitions,
1832 /// impl blocks, and modules. It is still parsed using the same code, just with
1833 /// different flags set, so that even when the input is wrong and produces a parse
1834 /// error, it still gets into the AST and the rest of the parser and
1835 /// type checker can run.
1836 #[derive(Clone, Copy)]
1837 pub(crate) struct FnParseMode {
1838 /// A function pointer that decides if, per-parameter `p`, `p` must have a
1839 /// pattern or just a type. This field affects parsing of the parameters list.
1842 /// fn foo(alef: A) -> X { X::new() }
1843 /// -----^^ affects parsing this part of the function signature
1845 /// if req_name returns false, then this name is optional
1850 /// if req_name returns true, this is an error
1853 /// Calling this function pointer should only return false if:
1855 /// * The item is being parsed inside of a trait definition.
1856 /// Within an impl block or a module, it should always evaluate
1858 /// * The span is from Edition 2015. In particular, you can get a
1859 /// 2015 span inside a 2021 crate using macros.
1860 pub req_name: ReqName,
1861 /// If this flag is set to `true`, then plain, semicolon-terminated function
1862 /// prototypes are not allowed here.
1865 /// fn foo(alef: A) -> X { X::new() }
1868 /// this is always allowed
1870 /// fn bar(alef: A, bet: B) -> X;
1873 /// if req_body is set to true, this is an error
1876 /// This field should only be set to false if the item is inside of a trait
1877 /// definition or extern block. Within an impl block or a module, it should
1878 /// always be set to true.
1882 /// Parsing of functions and methods.
1883 impl<'a> Parser<'a> {
1884 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1887 attrs: &mut Vec<Attribute>,
1888 fn_parse_mode: FnParseMode,
1891 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1892 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
1893 let ident = self.parse_ident()?; // `foo`
1894 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1896 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1897 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1899 let mut sig_hi = self.prev_token.span;
1900 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
1901 let fn_sig_span = sig_lo.to(sig_hi);
1902 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1905 /// Parse the "body
" of a function.
1906 /// This can either be `;` when there's no body,
1907 /// or e.g. a block when the function is a provided one.
1910 attrs: &mut Vec<Attribute>,
1914 ) -> PResult<'a, Option<P<Block>>> {
1915 let has_semi = if req_body {
1916 self.token.kind == TokenKind::Semi
1918 // Only include `;` in list of expected tokens if body is not required
1919 self.check(&TokenKind::Semi)
1921 let (inner_attrs, body) = if has_semi {
1922 // Include the trailing semicolon in the span of the signature
1923 self.expect_semi()?;
1924 *sig_hi = self.prev_token.span;
1926 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1927 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1928 } else if self.token.kind == token::Eq {
1929 // Recover `fn foo() = $expr;`.
1931 let eq_sp = self.prev_token.span;
1932 let _ = self.parse_expr()?;
1933 self.expect_semi()?; // `;`
1934 let span = eq_sp.to(self.prev_token.span);
1935 self.struct_span_err(span, "function body cannot be `
= expression
;`
")
1936 .multipart_suggestion(
1937 "surround the expression with `{` and `}` instead of `
=` and `
;`
",
1938 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }
".to_string())],
1939 Applicability::MachineApplicable,
1942 (Vec::new(), Some(self.mk_block_err(span)))
1944 let expected = if req_body {
1945 &[token::OpenDelim(token::Brace)][..]
1947 &[token::Semi, token::OpenDelim(token::Brace)]
1949 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
1950 if self.token.kind == token::CloseDelim(token::Brace) {
1951 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1952 // the AST for typechecking.
1953 err.span_label(ident.span, "while parsing this `
fn`
");
1961 attrs.extend(inner_attrs);
1965 /// Is the current token the start of an `FnHeader` / not a valid parse?
1967 /// `check_pub` adds additional `pub` to the checks in case users place it
1968 /// wrongly, can be used to ensure `pub` never comes after `default`.
1969 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
1970 // We use an over-approximation here.
1971 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1972 // `pub` is added in case users got confused with the ordering like `async pub fn`,
1973 // only if it wasn't preceded by `default` as `default pub` is invalid.
1974 let quals: &[Symbol] = if check_pub {
1975 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1977 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
1979 self.check_keyword(kw::Fn) // Definitely an `fn`.
1980 // `$qual fn` or `$qual $qual`:
1981 || quals.iter().any(|&kw| self.check_keyword(kw))
1982 && self.look_ahead(1, |t| {
1983 // `$qual fn`, e.g. `const fn` or `async fn`.
1984 t.is_keyword(kw::Fn)
1985 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1986 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
1987 // Rule out 2015 `const async: T = val`.
1989 // Rule out unsafe extern block.
1990 && !self.is_unsafe_foreign_mod())
1993 || self.check_keyword(kw::Extern)
1994 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1995 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1998 /// Parses all the "front matter
" (or "qualifiers
") for a `fn` declaration,
1999 /// up to and including the `fn` keyword. The formal grammar is:
2002 /// Extern = "extern" StringLit? ;
2003 /// FnQual = "const"? "async
"? "unsafe"? Extern? ;
2004 /// FnFrontMatter = FnQual "fn" ;
2007 /// `vis` represents the visibility that was already parsed, if any. Use
2008 /// `Visibility::Inherited` when no visibility is known.
2009 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2010 let sp_start = self.token.span;
2011 let constness = self.parse_constness();
2013 let async_start_sp = self.token.span;
2014 let asyncness = self.parse_asyncness();
2016 let unsafe_start_sp = self.token.span;
2017 let unsafety = self.parse_unsafety();
2019 let ext_start_sp = self.token.span;
2020 let ext = self.parse_extern();
2022 if let Async::Yes { span, .. } = asyncness {
2023 self.ban_async_in_2015(span);
2026 if !self.eat_keyword(kw::Fn) {
2027 // It is possible for `expect_one_of` to recover given the contents of
2028 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2029 // account for this.
2030 match self.expect_one_of(&[], &[]) {
2032 Ok(false) => unreachable!(),
2034 // Qualifier keywords ordering check
2040 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2041 // that the keyword is already present and the second instance should be removed.
2042 let wrong_kw = if self.check_keyword(kw::Const) {
2044 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2045 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2047 } else if self.check_keyword(kw::Async) {
2049 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2050 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2052 } else if self.check_keyword(kw::Unsafe) {
2054 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2055 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2061 // The keyword is already present, suggest removal of the second instance
2062 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2063 let original_kw = self
2064 .span_to_snippet(original_sp)
2065 .expect("Span extracted directly from keyword should always work
");
2067 err.span_suggestion(
2068 self.token.uninterpolated_span(),
2069 &format!("`{original_kw}` already used earlier
, remove this one
"),
2071 Applicability::MachineApplicable,
2073 .span_note(original_sp, &format!("`{original_kw}` first seen here
"));
2075 // The keyword has not been seen yet, suggest correct placement in the function front matter
2076 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2077 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2078 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2079 let misplaced_qual_sp = self.token.uninterpolated_span();
2080 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2082 err.span_suggestion(
2083 correct_pos_sp.to(misplaced_qual_sp),
2084 &format!("`{misplaced_qual}` must come before `{current_qual}`
"),
2085 format!("{misplaced_qual} {current_qual}
"),
2086 Applicability::MachineApplicable,
2087 ).note("keyword order
for functions declaration is `
default`
, `
pub`
, `
const`
, `async`
, `
unsafe`
, `
extern`
");
2090 // Recover incorrect visibility order such as `async pub`
2091 else if self.check_keyword(kw::Pub) {
2092 let sp = sp_start.to(self.prev_token.span);
2093 if let Ok(snippet) = self.span_to_snippet(sp) {
2094 let current_vis = match self.parse_visibility(FollowedByType::No) {
2101 let vs = pprust::vis_to_string(¤t_vis);
2102 let vs = vs.trim_end();
2104 // There was no explicit visibility
2105 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2106 err.span_suggestion(
2107 sp_start.to(self.prev_token.span),
2108 &format!("visibility `{vs}` must come before `{snippet}`
"),
2109 format!("{vs} {snippet}
"),
2110 Applicability::MachineApplicable,
2113 // There was an explicit visibility
2115 err.span_suggestion(
2117 "there is already a visibility modifier
, remove one
",
2119 Applicability::MachineApplicable,
2121 .span_note(orig_vis.span, "explicit visibility first seen here
");
2130 Ok(FnHeader { constness, unsafety, asyncness, ext })
2133 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2134 fn ban_async_in_2015(&self, span: Span) {
2135 if span.rust_2015() {
2136 let diag = self.diagnostic();
2137 struct_span_err!(diag, span, E0670, "`async
fn` is not permitted
in Rust
2015")
2138 .span_label(span, "to
use `async
fn`
, switch to Rust
2018 or later
")
2139 .help_use_latest_edition()
2144 /// Parses the parameter list and result type of a function declaration.
2145 pub(super) fn parse_fn_decl(
2148 ret_allow_plus: AllowPlus,
2149 recover_return_sign: RecoverReturnSign,
2150 ) -> PResult<'a, P<FnDecl>> {
2152 inputs: self.parse_fn_params(req_name)?,
2153 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2157 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2158 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2159 let mut first_param = true;
2160 // Parse the arguments, starting out with `self` being allowed...
2161 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2162 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2164 let lo = p.prev_token.span;
2165 // Skip every token until next possible arg or end.
2166 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
2167 // Create a placeholder argument for proper arg count (issue #34264).
2168 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2170 // ...now that we've parsed the first argument, `self` is no longer allowed.
2171 first_param = false;
2174 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2175 self.deduplicate_recovered_params_names(&mut params);
2179 /// Parses a single function parameter.
2181 /// - `self` is syntactically allowed when `first_param` holds.
2182 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2183 let lo = self.token.span;
2184 let attrs = self.parse_outer_attributes()?;
2185 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2186 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2187 if let Some(mut param) = this.parse_self_param()? {
2188 param.attrs = attrs.into();
2189 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2190 return Ok((res?, TrailingToken::None));
2193 let is_name_required = match this.token.kind {
2194 token::DotDotDot => false,
2195 _ => req_name(this.token.span.edition()),
2197 let (pat, ty) = if is_name_required || this.is_named_param() {
2198 debug!("parse_param_general
parse_pat (is_name_required
:{}
)", is_name_required);
2200 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2202 let mut err = this.unexpected::<()>().unwrap_err();
2203 return if let Some(ident) =
2204 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2207 Ok((dummy_arg(ident), TrailingToken::None))
2213 this.eat_incorrect_doc_comment_for_param_type();
2214 (pat, this.parse_ty_for_param()?)
2216 debug!("parse_param_general ident_to_pat
");
2217 let parser_snapshot_before_ty = this.clone();
2218 this.eat_incorrect_doc_comment_for_param_type();
2219 let mut ty = this.parse_ty_for_param();
2221 && this.token != token::Comma
2222 && this.token != token::CloseDelim(token::Paren)
2224 // This wasn't actually a type, but a pattern looking like a type,
2225 // so we are going to rollback and re-parse for recovery.
2226 ty = this.unexpected();
2230 let ident = Ident::new(kw::Empty, this.prev_token.span);
2231 let bm = BindingMode::ByValue(Mutability::Not);
2232 let pat = this.mk_pat_ident(ty.span, bm, ident);
2235 // If this is a C-variadic argument and we hit an error, return the error.
2236 Err(err) if this.token == token::DotDotDot => return Err(err),
2237 // Recover from attempting to parse the argument as a type without pattern.
2240 *this = parser_snapshot_before_ty;
2241 this.recover_arg_parse()?
2246 let span = lo.until(this.token.span);
2250 attrs: attrs.into(),
2251 id: ast::DUMMY_NODE_ID,
2252 is_placeholder: false,
2257 TrailingToken::None,
2262 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2263 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2264 // Extract an identifier *after* having confirmed that the token is one.
2265 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2266 Some((ident, false)) => {
2270 _ => unreachable!(),
2272 // Is `self` `n` tokens ahead?
2273 let is_isolated_self = |this: &Self, n| {
2274 this.is_keyword_ahead(n, &[kw::SelfLower])
2275 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2277 // Is `mut self` `n` tokens ahead?
2278 let is_isolated_mut_self =
2279 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2280 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2281 let parse_self_possibly_typed = |this: &mut Self, m| {
2282 let eself_ident = expect_self_ident(this);
2283 let eself_hi = this.prev_token.span;
2284 let eself = if this.eat(&token::Colon) {
2285 SelfKind::Explicit(this.parse_ty()?, m)
2289 Ok((eself, eself_ident, eself_hi))
2291 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2292 let recover_self_ptr = |this: &mut Self| {
2293 let msg = "cannot pass `
self` by raw pointer
";
2294 let span = this.token.span;
2295 this.struct_span_err(span, msg).span_label(span, msg).emit();
2297 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2300 // Parse optional `self` parameter of a method.
2301 // Only a limited set of initial token sequences is considered `self` parameters; anything
2302 // else is parsed as a normal function parameter list, so some lookahead is required.
2303 let eself_lo = self.token.span;
2304 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2305 token::BinOp(token::And) => {
2306 let eself = if is_isolated_self(self, 1) {
2309 SelfKind::Region(None, Mutability::Not)
2310 } else if is_isolated_mut_self(self, 1) {
2314 SelfKind::Region(None, Mutability::Mut)
2315 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2318 let lt = self.expect_lifetime();
2319 SelfKind::Region(Some(lt), Mutability::Not)
2320 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2323 let lt = self.expect_lifetime();
2325 SelfKind::Region(Some(lt), Mutability::Mut)
2330 (eself, expect_self_ident(self), self.prev_token.span)
2333 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2335 recover_self_ptr(self)?
2337 // `*mut self` and `*const self`
2338 token::BinOp(token::Star)
2339 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2343 recover_self_ptr(self)?
2345 // `self` and `self: TYPE`
2346 token::Ident(..) if is_isolated_self(self, 0) => {
2347 parse_self_possibly_typed(self, Mutability::Not)?
2349 // `mut self` and `mut self: TYPE`
2350 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2352 parse_self_possibly_typed(self, Mutability::Mut)?
2354 _ => return Ok(None),
2357 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2358 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2361 fn is_named_param(&self) -> bool {
2362 let offset = match self.token.kind {
2363 token::Interpolated(ref nt) => match **nt {
2364 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2367 token::BinOp(token::And) | token::AndAnd => 1,
2368 _ if self.token.is_keyword(kw::Mut) => 1,
2372 self.look_ahead(offset, |t| t.is_ident())
2373 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2376 fn recover_first_param(&mut self) -> &'static str {
2378 .parse_outer_attributes()
2379 .and_then(|_| self.parse_self_param())
2380 .map_err(|e| e.cancel())
2382 Ok(Some(_)) => "method
",
2388 enum IsMacroRulesItem {
2389 Yes { has_bang: bool },