]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_parse/src/parser/item.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / compiler / rustc_parse / src / parser / item.rs
1 use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error};
2 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
3 use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
4
5 use rustc_ast::ast::*;
6 use rustc_ast::ptr::P;
7 use rustc_ast::token::{self, Delimiter, 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::{BindingAnnotation, 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;
22
23 use std::convert::TryFrom;
24 use std::mem;
25
26 impl<'a> Parser<'a> {
27 /// Parses a source module as a crate. This is the main entry point for the parser.
28 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
29 let (attrs, items, spans) = self.parse_mod(&token::Eof)?;
30 Ok(ast::Crate { attrs, items, spans, id: DUMMY_NODE_ID, is_placeholder: false })
31 }
32
33 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
34 fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemInfo> {
35 let unsafety = self.parse_unsafety();
36 self.expect_keyword(kw::Mod)?;
37 let id = self.parse_ident()?;
38 let mod_kind = if self.eat(&token::Semi) {
39 ModKind::Unloaded
40 } else {
41 self.expect(&token::OpenDelim(Delimiter::Brace))?;
42 let (inner_attrs, items, inner_span) =
43 self.parse_mod(&token::CloseDelim(Delimiter::Brace))?;
44 attrs.extend(inner_attrs);
45 ModKind::Loaded(items, Inline::Yes, inner_span)
46 };
47 Ok((id, ItemKind::Mod(unsafety, mod_kind)))
48 }
49
50 /// Parses the contents of a module (inner attributes followed by module items).
51 pub fn parse_mod(
52 &mut self,
53 term: &TokenKind,
54 ) -> PResult<'a, (AttrVec, Vec<P<Item>>, ModSpans)> {
55 let lo = self.token.span;
56 let attrs = self.parse_inner_attributes()?;
57
58 let post_attr_lo = self.token.span;
59 let mut items = vec![];
60 while let Some(item) = self.parse_item(ForceCollect::No)? {
61 items.push(item);
62 self.maybe_consume_incorrect_semicolon(&items);
63 }
64
65 if !self.eat(term) {
66 let token_str = super::token_descr(&self.token);
67 if !self.maybe_consume_incorrect_semicolon(&items) {
68 let msg = &format!("expected item, found {token_str}");
69 let mut err = self.struct_span_err(self.token.span, msg);
70 let label = if self.is_kw_followed_by_ident(kw::Let) {
71 "consider using `const` or `static` instead of `let` for global variables"
72 } else {
73 "expected item"
74 };
75 err.span_label(self.token.span, label);
76 return Err(err);
77 }
78 }
79
80 let inject_use_span = post_attr_lo.data().with_hi(post_attr_lo.lo());
81 let mod_spans = ModSpans { inner_span: lo.to(self.prev_token.span), inject_use_span };
82 Ok((attrs, items, mod_spans))
83 }
84 }
85
86 pub(super) type ItemInfo = (Ident, ItemKind);
87
88 impl<'a> Parser<'a> {
89 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
90 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
91 self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P))
92 }
93
94 fn parse_item_(
95 &mut self,
96 fn_parse_mode: FnParseMode,
97 force_collect: ForceCollect,
98 ) -> PResult<'a, Option<Item>> {
99 let attrs = self.parse_outer_attributes()?;
100 self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect)
101 }
102
103 pub(super) fn parse_item_common(
104 &mut self,
105 attrs: AttrWrapper,
106 mac_allowed: bool,
107 attrs_allowed: bool,
108 fn_parse_mode: FnParseMode,
109 force_collect: ForceCollect,
110 ) -> PResult<'a, Option<Item>> {
111 // Don't use `maybe_whole` so that we have precise control
112 // over when we bump the parser
113 if let token::Interpolated(nt) = &self.token.kind && let token::NtItem(item) = &**nt {
114 let mut item = item.clone();
115 self.bump();
116
117 attrs.prepend_to_nt_inner(&mut item.attrs);
118 return Ok(Some(item.into_inner()));
119 };
120
121 let mut unclosed_delims = vec![];
122 let item =
123 self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| {
124 let item =
125 this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode);
126 unclosed_delims.append(&mut this.unclosed_delims);
127 Ok((item?, TrailingToken::None))
128 })?;
129
130 self.unclosed_delims.append(&mut unclosed_delims);
131 Ok(item)
132 }
133
134 fn parse_item_common_(
135 &mut self,
136 mut attrs: AttrVec,
137 mac_allowed: bool,
138 attrs_allowed: bool,
139 fn_parse_mode: FnParseMode,
140 ) -> PResult<'a, Option<Item>> {
141 let lo = self.token.span;
142 let vis = self.parse_visibility(FollowedByType::No)?;
143 let mut def = self.parse_defaultness();
144 let kind =
145 self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, fn_parse_mode)?;
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));
152 }
153
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);
157 if !attrs_allowed {
158 self.recover_attrs_no_item(&attrs)?;
159 }
160 Ok(None)
161 }
162
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 {
166 return;
167 }
168 let vs = pprust::vis_to_string(&vis);
169 let vs = vs.trim_end();
170 self.struct_span_err(vis.span, &format!("visibility `{vs}` is not followed by an item"))
171 .span_label(vis.span, "the visibility")
172 .help(&format!("you likely meant to define an item, e.g., `{vs} fn foo() {{}}`"))
173 .emit();
174 }
175
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`")
182 .emit();
183 }
184 }
185
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`")
193 .emit();
194 }
195 }
196
197 /// Parses one of the items allowed by the flags.
198 fn parse_item_kind(
199 &mut self,
200 attrs: &mut AttrVec,
201 macros_allowed: bool,
202 lo: Span,
203 vis: &Visibility,
204 def: &mut Defaultness,
205 fn_parse_mode: FnParseMode,
206 ) -> PResult<'a, Option<ItemInfo>> {
207 let def_final = def == &Defaultness::Final;
208 let mut def = || mem::replace(def, Defaultness::Final);
209
210 let info = if self.eat_keyword(kw::Use) {
211 self.parse_use_item()?
212 } else if self.check_fn_front_matter(def_final) {
213 // FUNCTION ITEM
214 let (ident, sig, generics, body) = self.parse_fn(attrs, fn_parse_mode, lo, vis)?;
215 (ident, ItemKind::Fn(Box::new(Fn { defaultness: def(), sig, generics, body })))
216 } else if self.eat_keyword(kw::Extern) {
217 if self.eat_keyword(kw::Crate) {
218 // EXTERN CRATE
219 self.parse_item_extern_crate()?
220 } else {
221 // EXTERN BLOCK
222 self.parse_item_foreign_mod(attrs, Unsafe::No)?
223 }
224 } else if self.is_unsafe_foreign_mod() {
225 // EXTERN BLOCK
226 let unsafety = self.parse_unsafety();
227 self.expect_keyword(kw::Extern)?;
228 self.parse_item_foreign_mod(attrs, unsafety)?
229 } else if self.is_static_global() {
230 // STATIC ITEM
231 self.bump(); // `static`
232 let m = self.parse_mutability();
233 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
234 (ident, ItemKind::Static(ty, m, expr))
235 } else if let Const::Yes(const_span) = self.parse_constness() {
236 // CONST ITEM
237 if self.token.is_keyword(kw::Impl) {
238 // recover from `const impl`, suggest `impl const`
239 self.recover_const_impl(const_span, attrs, def())?
240 } else {
241 self.recover_const_mut(const_span);
242 let (ident, ty, expr) = self.parse_item_global(None)?;
243 (ident, ItemKind::Const(def(), ty, expr))
244 }
245 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
246 // TRAIT ITEM
247 self.parse_item_trait(attrs, lo)?
248 } else if self.check_keyword(kw::Impl)
249 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
250 {
251 // IMPL ITEM
252 self.parse_item_impl(attrs, def())?
253 } else if self.check_keyword(kw::Mod)
254 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
255 {
256 // MODULE ITEM
257 self.parse_item_mod(attrs)?
258 } else if self.eat_keyword(kw::Type) {
259 // TYPE ITEM
260 self.parse_type_alias(def())?
261 } else if self.eat_keyword(kw::Enum) {
262 // ENUM ITEM
263 self.parse_item_enum()?
264 } else if self.eat_keyword(kw::Struct) {
265 // STRUCT ITEM
266 self.parse_item_struct()?
267 } else if self.is_kw_followed_by_ident(kw::Union) {
268 // UNION ITEM
269 self.bump(); // `union`
270 self.parse_item_union()?
271 } else if self.eat_keyword(kw::Macro) {
272 // MACROS 2.0 ITEM
273 self.parse_item_decl_macro(lo)?
274 } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() {
275 // MACRO_RULES ITEM
276 self.parse_item_macro_rules(vis, has_bang)?
277 } else if self.isnt_macro_invocation()
278 && (self.token.is_ident_named(sym::import)
279 || self.token.is_ident_named(sym::using)
280 || self.token.is_ident_named(sym::include)
281 || self.token.is_ident_named(sym::require))
282 {
283 return self.recover_import_as_use();
284 } else if self.isnt_macro_invocation() && vis.kind.is_pub() {
285 self.recover_missing_kw_before_item()?;
286 return Ok(None);
287 } else if macros_allowed && self.check_path() {
288 // MACRO INVOCATION ITEM
289 (Ident::empty(), ItemKind::MacCall(P(self.parse_item_macro(vis)?)))
290 } else {
291 return Ok(None);
292 };
293 Ok(Some(info))
294 }
295
296 fn recover_import_as_use(&mut self) -> PResult<'a, Option<(Ident, ItemKind)>> {
297 let span = self.token.span;
298 let token_name = super::token_descr(&self.token);
299 let snapshot = self.create_snapshot_for_diagnostic();
300 self.bump();
301 match self.parse_use_item() {
302 Ok(u) => {
303 self.struct_span_err(span, format!("expected item, found {token_name}"))
304 .span_suggestion_short(
305 span,
306 "items are imported using the `use` keyword",
307 "use",
308 Applicability::MachineApplicable,
309 )
310 .emit();
311 Ok(Some(u))
312 }
313 Err(e) => {
314 e.cancel();
315 self.restore_snapshot(snapshot);
316 Ok(None)
317 }
318 }
319 }
320
321 fn parse_use_item(&mut self) -> PResult<'a, (Ident, ItemKind)> {
322 let tree = self.parse_use_tree()?;
323 if let Err(mut e) = self.expect_semi() {
324 match tree.kind {
325 UseTreeKind::Glob => {
326 e.note("the wildcard token must be last on the path");
327 }
328 UseTreeKind::Nested(..) => {
329 e.note("glob-like brace syntax must be last on the path");
330 }
331 _ => (),
332 }
333 return Err(e);
334 }
335 Ok((Ident::empty(), ItemKind::Use(tree)))
336 }
337
338 /// When parsing a statement, would the start of a path be an item?
339 pub(super) fn is_path_start_item(&mut self) -> bool {
340 self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
341 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
342 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
343 || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac`
344 }
345
346 /// Are we sure this could not possibly be a macro invocation?
347 fn isnt_macro_invocation(&mut self) -> bool {
348 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
349 }
350
351 /// Recover on encountering a struct or method definition where the user
352 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
353 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
354 // Space between `pub` keyword and the identifier
355 //
356 // pub S {}
357 // ^^^ `sp` points here
358 let sp = self.prev_token.span.between(self.token.span);
359 let full_sp = self.prev_token.span.to(self.token.span);
360 let ident_sp = self.token.span;
361 if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace)) {
362 // possible public struct definition where `struct` was forgotten
363 let ident = self.parse_ident().unwrap();
364 let msg = format!("add `struct` here to parse `{ident}` as a public struct");
365 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
366 err.span_suggestion_short(
367 sp,
368 &msg,
369 " struct ",
370 Applicability::MaybeIncorrect, // speculative
371 );
372 Err(err)
373 } else if self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Parenthesis)) {
374 let ident = self.parse_ident().unwrap();
375 self.bump(); // `(`
376 let kw_name = self.recover_first_param();
377 self.consume_block(Delimiter::Parenthesis, ConsumeClosingDelim::Yes);
378 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
379 self.eat_to_tokens(&[&token::OpenDelim(Delimiter::Brace)]);
380 self.bump(); // `{`
381 ("fn", kw_name, false)
382 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
383 self.bump(); // `{`
384 ("fn", kw_name, false)
385 } else if self.check(&token::Colon) {
386 let kw = "struct";
387 (kw, kw, false)
388 } else {
389 ("fn` or `struct", "function or struct", true)
390 };
391
392 let msg = format!("missing `{kw}` for {kw_name} definition");
393 let mut err = self.struct_span_err(sp, &msg);
394 if !ambiguous {
395 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
396 let suggestion =
397 format!("add `{kw}` here to parse `{ident}` as a public {kw_name}");
398 err.span_suggestion_short(
399 sp,
400 &suggestion,
401 format!(" {kw} "),
402 Applicability::MachineApplicable,
403 );
404 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
405 err.span_suggestion(
406 full_sp,
407 "if you meant to call a macro, try",
408 format!("{}!", snippet),
409 // this is the `ambiguous` conditional branch
410 Applicability::MaybeIncorrect,
411 );
412 } else {
413 err.help(
414 "if you meant to call a macro, remove the `pub` \
415 and add a trailing `!` after the identifier",
416 );
417 }
418 Err(err)
419 } else if self.look_ahead(1, |t| *t == token::Lt) {
420 let ident = self.parse_ident().unwrap();
421 self.eat_to_tokens(&[&token::Gt]);
422 self.bump(); // `>`
423 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(Delimiter::Parenthesis)) {
424 ("fn", self.recover_first_param(), false)
425 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
426 ("struct", "struct", false)
427 } else {
428 ("fn` or `struct", "function or struct", true)
429 };
430 let msg = format!("missing `{kw}` for {kw_name} definition");
431 let mut err = self.struct_span_err(sp, &msg);
432 if !ambiguous {
433 err.span_suggestion_short(
434 sp,
435 &format!("add `{kw}` here to parse `{ident}` as a public {kw_name}"),
436 format!(" {} ", kw),
437 Applicability::MachineApplicable,
438 );
439 }
440 Err(err)
441 } else {
442 Ok(())
443 }
444 }
445
446 /// Parses an item macro, e.g., `item!();`.
447 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
448 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
449 self.expect(&token::Not)?; // `!`
450 match self.parse_mac_args() {
451 // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
452 Ok(args) => {
453 self.eat_semi_for_macro_if_needed(&args);
454 self.complain_if_pub_macro(vis, false);
455 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
456 }
457
458 Err(mut err) => {
459 // Maybe the user misspelled `macro_rules` (issue #91227)
460 if self.token.is_ident()
461 && path.segments.len() == 1
462 && lev_distance("macro_rules", &path.segments[0].ident.to_string(), 3).is_some()
463 {
464 err.span_suggestion(
465 path.span,
466 "perhaps you meant to define a macro",
467 "macro_rules",
468 Applicability::MachineApplicable,
469 );
470 }
471 Err(err)
472 }
473 }
474 }
475
476 /// Recover if we parsed attributes and expected an item but there was none.
477 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
478 let ([start @ end] | [start, .., end]) = attrs else {
479 return Ok(());
480 };
481 let msg = if end.is_doc_comment() {
482 "expected item after doc comment"
483 } else {
484 "expected item after attributes"
485 };
486 let mut err = self.struct_span_err(end.span, msg);
487 if end.is_doc_comment() {
488 err.span_label(end.span, "this doc comment doesn't document anything");
489 }
490 if end.meta_kind().is_some() {
491 if self.token.kind == TokenKind::Semi {
492 err.span_suggestion_verbose(
493 self.token.span,
494 "consider removing this semicolon",
495 "",
496 Applicability::MaybeIncorrect,
497 );
498 }
499 }
500 if let [.., penultimate, _] = attrs {
501 err.span_label(start.span.to(penultimate.span), "other attributes here");
502 }
503 Err(err)
504 }
505
506 fn is_async_fn(&self) -> bool {
507 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
508 }
509
510 fn parse_polarity(&mut self) -> ast::ImplPolarity {
511 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
512 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
513 self.bump(); // `!`
514 ast::ImplPolarity::Negative(self.prev_token.span)
515 } else {
516 ast::ImplPolarity::Positive
517 }
518 }
519
520 /// Parses an implementation item.
521 ///
522 /// ```ignore (illustrative)
523 /// impl<'a, T> TYPE { /* impl items */ }
524 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
525 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
526 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
527 /// ```
528 ///
529 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
530 /// ```ebnf
531 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
532 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
533 /// ```
534 fn parse_item_impl(
535 &mut self,
536 attrs: &mut AttrVec,
537 defaultness: Defaultness,
538 ) -> PResult<'a, ItemInfo> {
539 let unsafety = self.parse_unsafety();
540 self.expect_keyword(kw::Impl)?;
541
542 // First, parse generic parameters if necessary.
543 let mut generics = if self.choose_generics_over_qpath(0) {
544 self.parse_generics()?
545 } else {
546 let mut generics = Generics::default();
547 // impl A for B {}
548 // /\ this is where `generics.span` should point when there are no type params.
549 generics.span = self.prev_token.span.shrink_to_hi();
550 generics
551 };
552
553 let constness = self.parse_constness();
554 if let Const::Yes(span) = constness {
555 self.sess.gated_spans.gate(sym::const_trait_impl, span);
556 }
557
558 let polarity = self.parse_polarity();
559
560 // Parse both types and traits as a type, then reinterpret if necessary.
561 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
562 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
563 {
564 let span = self.prev_token.span.between(self.token.span);
565 self.struct_span_err(span, "missing trait in a trait impl")
566 .span_suggestion(
567 span,
568 "add a trait here",
569 " Trait ",
570 Applicability::HasPlaceholders,
571 )
572 .span_suggestion(
573 span.to(self.token.span),
574 "for an inherent impl, drop this `for`",
575 "",
576 Applicability::MaybeIncorrect,
577 )
578 .emit();
579 P(Ty {
580 kind: TyKind::Path(None, err_path(span)),
581 span,
582 id: DUMMY_NODE_ID,
583 tokens: None,
584 })
585 } else {
586 self.parse_ty_with_generics_recovery(&generics)?
587 };
588
589 // If `for` is missing we try to recover.
590 let has_for = self.eat_keyword(kw::For);
591 let missing_for_span = self.prev_token.span.between(self.token.span);
592
593 let ty_second = if self.token == token::DotDot {
594 // We need to report this error after `cfg` expansion for compatibility reasons
595 self.bump(); // `..`, do not add it to expected tokens
596 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
597 } else if has_for || self.token.can_begin_type() {
598 Some(self.parse_ty()?)
599 } else {
600 None
601 };
602
603 generics.where_clause = self.parse_where_clause()?;
604
605 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item(ForceCollect::No))?;
606
607 let item_kind = match ty_second {
608 Some(ty_second) => {
609 // impl Trait for Type
610 if !has_for {
611 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
612 .span_suggestion_short(
613 missing_for_span,
614 "add `for` here",
615 " for ",
616 Applicability::MachineApplicable,
617 )
618 .emit();
619 }
620
621 let ty_first = ty_first.into_inner();
622 let path = match ty_first.kind {
623 // This notably includes paths passed through `ty` macro fragments (#46438).
624 TyKind::Path(None, path) => path,
625 _ => {
626 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
627 err_path(ty_first.span)
628 }
629 };
630 let trait_ref = TraitRef { path, ref_id: ty_first.id };
631
632 ItemKind::Impl(Box::new(Impl {
633 unsafety,
634 polarity,
635 defaultness,
636 constness,
637 generics,
638 of_trait: Some(trait_ref),
639 self_ty: ty_second,
640 items: impl_items,
641 }))
642 }
643 None => {
644 // impl Type
645 ItemKind::Impl(Box::new(Impl {
646 unsafety,
647 polarity,
648 defaultness,
649 constness,
650 generics,
651 of_trait: None,
652 self_ty: ty_first,
653 items: impl_items,
654 }))
655 }
656 };
657
658 Ok((Ident::empty(), item_kind))
659 }
660
661 fn parse_item_list<T>(
662 &mut self,
663 attrs: &mut AttrVec,
664 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
665 ) -> PResult<'a, Vec<T>> {
666 let open_brace_span = self.token.span;
667 self.expect(&token::OpenDelim(Delimiter::Brace))?;
668 attrs.extend(self.parse_inner_attributes()?);
669
670 let mut items = Vec::new();
671 while !self.eat(&token::CloseDelim(Delimiter::Brace)) {
672 if self.recover_doc_comment_before_brace() {
673 continue;
674 }
675 match parse_item(self) {
676 Ok(None) => {
677 let is_unnecessary_semicolon = !items.is_empty()
678 // When the close delim is `)` in a case like the following, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
679 // but the actual `token.kind` is `token::CloseDelim(Delimiter::Bracket)`.
680 // This is because the `token.kind` of the close delim is treated as the same as
681 // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
682 // Therefore, `token.kind` should not be compared here.
683 //
684 // issue-60075.rs
685 // ```
686 // trait T {
687 // fn qux() -> Option<usize> {
688 // let _ = if true {
689 // });
690 // ^ this close delim
691 // Some(4)
692 // }
693 // ```
694 && self
695 .span_to_snippet(self.prev_token.span)
696 .map_or(false, |snippet| snippet == "}")
697 && self.token.kind == token::Semi;
698 let semicolon_span = self.token.span;
699 // We have to bail or we'll potentially never make progress.
700 let non_item_span = self.token.span;
701 let is_let = self.token.is_keyword(kw::Let);
702
703 let mut err = self.struct_span_err(non_item_span, "non-item in item list");
704 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
705 if is_let {
706 err.span_suggestion(
707 non_item_span,
708 "consider using `const` instead of `let` for associated const",
709 "const",
710 Applicability::MachineApplicable,
711 );
712 } else {
713 err.span_label(open_brace_span, "item list starts here")
714 .span_label(non_item_span, "non-item starts here")
715 .span_label(self.prev_token.span, "item list ends here");
716 }
717 if is_unnecessary_semicolon {
718 err.span_suggestion(
719 semicolon_span,
720 "consider removing this semicolon",
721 "",
722 Applicability::MaybeIncorrect,
723 );
724 }
725 err.emit();
726 break;
727 }
728 Ok(Some(item)) => items.extend(item),
729 Err(mut err) => {
730 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::Yes);
731 err.span_label(open_brace_span, "while parsing this item list starting here")
732 .span_label(self.prev_token.span, "the item list ends here")
733 .emit();
734 break;
735 }
736 }
737 }
738 Ok(items)
739 }
740
741 /// Recover on a doc comment before `}`.
742 fn recover_doc_comment_before_brace(&mut self) -> bool {
743 if let token::DocComment(..) = self.token.kind {
744 if self.look_ahead(1, |tok| tok == &token::CloseDelim(Delimiter::Brace)) {
745 struct_span_err!(
746 self.diagnostic(),
747 self.token.span,
748 E0584,
749 "found a documentation comment that doesn't document anything",
750 )
751 .span_label(self.token.span, "this doc comment doesn't document anything")
752 .help(
753 "doc comments must come before what they document, maybe a \
754 comment was intended with `//`?",
755 )
756 .emit();
757 self.bump();
758 return true;
759 }
760 }
761 false
762 }
763
764 /// Parses defaultness (i.e., `default` or nothing).
765 fn parse_defaultness(&mut self) -> Defaultness {
766 // We are interested in `default` followed by another identifier.
767 // However, we must avoid keywords that occur as binary operators.
768 // Currently, the only applicable keyword is `as` (`default as Ty`).
769 if self.check_keyword(kw::Default)
770 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
771 {
772 self.bump(); // `default`
773 Defaultness::Default(self.prev_token.uninterpolated_span())
774 } else {
775 Defaultness::Final
776 }
777 }
778
779 /// Is this an `(unsafe auto? | auto) trait` item?
780 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
781 // auto trait
782 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
783 // unsafe auto trait
784 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
785 }
786
787 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
788 fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
789 let unsafety = self.parse_unsafety();
790 // Parse optional `auto` prefix.
791 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
792
793 self.expect_keyword(kw::Trait)?;
794 let ident = self.parse_ident()?;
795 let mut generics = self.parse_generics()?;
796
797 // Parse optional colon and supertrait bounds.
798 let had_colon = self.eat(&token::Colon);
799 let span_at_colon = self.prev_token.span;
800 let bounds = if had_colon {
801 self.parse_generic_bounds(Some(self.prev_token.span))?
802 } else {
803 Vec::new()
804 };
805
806 let span_before_eq = self.prev_token.span;
807 if self.eat(&token::Eq) {
808 // It's a trait alias.
809 if had_colon {
810 let span = span_at_colon.to(span_before_eq);
811 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
812 }
813
814 let bounds = self.parse_generic_bounds(None)?;
815 generics.where_clause = self.parse_where_clause()?;
816 self.expect_semi()?;
817
818 let whole_span = lo.to(self.prev_token.span);
819 if is_auto == IsAuto::Yes {
820 let msg = "trait aliases cannot be `auto`";
821 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
822 }
823 if let Unsafe::Yes(_) = unsafety {
824 let msg = "trait aliases cannot be `unsafe`";
825 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
826 }
827
828 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
829
830 Ok((ident, ItemKind::TraitAlias(generics, bounds)))
831 } else {
832 // It's a normal trait.
833 generics.where_clause = self.parse_where_clause()?;
834 let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
835 Ok((
836 ident,
837 ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
838 ))
839 }
840 }
841
842 pub fn parse_impl_item(
843 &mut self,
844 force_collect: ForceCollect,
845 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
846 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
847 self.parse_assoc_item(fn_parse_mode, force_collect)
848 }
849
850 pub fn parse_trait_item(
851 &mut self,
852 force_collect: ForceCollect,
853 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
854 let fn_parse_mode =
855 FnParseMode { req_name: |edition| edition >= Edition::Edition2018, req_body: false };
856 self.parse_assoc_item(fn_parse_mode, force_collect)
857 }
858
859 /// Parses associated items.
860 fn parse_assoc_item(
861 &mut self,
862 fn_parse_mode: FnParseMode,
863 force_collect: ForceCollect,
864 ) -> PResult<'a, Option<Option<P<AssocItem>>>> {
865 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
866 |Item { attrs, id, span, vis, ident, kind, tokens }| {
867 let kind = match AssocItemKind::try_from(kind) {
868 Ok(kind) => kind,
869 Err(kind) => match kind {
870 ItemKind::Static(a, _, b) => {
871 self.struct_span_err(span, "associated `static` items are not allowed")
872 .emit();
873 AssocItemKind::Const(Defaultness::Final, a, b)
874 }
875 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
876 },
877 };
878 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
879 },
880 ))
881 }
882
883 /// Parses a `type` alias with the following grammar:
884 /// ```ebnf
885 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
886 /// ```
887 /// The `"type"` has already been eaten.
888 fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
889 let ident = self.parse_ident()?;
890 let mut generics = self.parse_generics()?;
891
892 // Parse optional colon and param bounds.
893 let bounds =
894 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
895 let before_where_clause = self.parse_where_clause()?;
896
897 let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
898
899 let after_where_clause = self.parse_where_clause()?;
900
901 let where_clauses = (
902 TyAliasWhereClause(before_where_clause.has_where_token, before_where_clause.span),
903 TyAliasWhereClause(after_where_clause.has_where_token, after_where_clause.span),
904 );
905 let where_predicates_split = before_where_clause.predicates.len();
906 let mut predicates = before_where_clause.predicates;
907 predicates.extend(after_where_clause.predicates.into_iter());
908 let where_clause = WhereClause {
909 has_where_token: before_where_clause.has_where_token
910 || after_where_clause.has_where_token,
911 predicates,
912 span: DUMMY_SP,
913 };
914 generics.where_clause = where_clause;
915
916 self.expect_semi()?;
917
918 Ok((
919 ident,
920 ItemKind::TyAlias(Box::new(TyAlias {
921 defaultness,
922 generics,
923 where_clauses,
924 where_predicates_split,
925 bounds,
926 ty,
927 })),
928 ))
929 }
930
931 /// Parses a `UseTree`.
932 ///
933 /// ```text
934 /// USE_TREE = [`::`] `*` |
935 /// [`::`] `{` USE_TREE_LIST `}` |
936 /// PATH `::` `*` |
937 /// PATH `::` `{` USE_TREE_LIST `}` |
938 /// PATH [`as` IDENT]
939 /// ```
940 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
941 let lo = self.token.span;
942
943 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
944 let kind = if self.check(&token::OpenDelim(Delimiter::Brace))
945 || self.check(&token::BinOp(token::Star))
946 || self.is_import_coupler()
947 {
948 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
949 let mod_sep_ctxt = self.token.span.ctxt();
950 if self.eat(&token::ModSep) {
951 prefix
952 .segments
953 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
954 }
955
956 self.parse_use_tree_glob_or_nested()?
957 } else {
958 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
959 prefix = self.parse_path(PathStyle::Mod)?;
960
961 if self.eat(&token::ModSep) {
962 self.parse_use_tree_glob_or_nested()?
963 } else {
964 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
965 }
966 };
967
968 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
969 }
970
971 /// Parses `*` or `{...}`.
972 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
973 Ok(if self.eat(&token::BinOp(token::Star)) {
974 UseTreeKind::Glob
975 } else {
976 UseTreeKind::Nested(self.parse_use_tree_list()?)
977 })
978 }
979
980 /// Parses a `UseTreeKind::Nested(list)`.
981 ///
982 /// ```text
983 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
984 /// ```
985 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
986 self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
987 .map(|(r, _)| r)
988 }
989
990 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
991 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
992 }
993
994 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
995 match self.token.ident() {
996 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
997 self.bump();
998 Ok(ident)
999 }
1000 _ => self.parse_ident(),
1001 }
1002 }
1003
1004 /// Parses `extern crate` links.
1005 ///
1006 /// # Examples
1007 ///
1008 /// ```ignore (illustrative)
1009 /// extern crate foo;
1010 /// extern crate bar as foo;
1011 /// ```
1012 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
1013 // Accept `extern crate name-like-this` for better diagnostics
1014 let orig_name = self.parse_crate_name_with_dashes()?;
1015 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
1016 (rename, Some(orig_name.name))
1017 } else {
1018 (orig_name, None)
1019 };
1020 self.expect_semi()?;
1021 Ok((item_name, ItemKind::ExternCrate(orig_name)))
1022 }
1023
1024 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
1025 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
1026 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
1027 in the code";
1028 let mut ident = if self.token.is_keyword(kw::SelfLower) {
1029 self.parse_path_segment_ident()
1030 } else {
1031 self.parse_ident()
1032 }?;
1033 let mut idents = vec![];
1034 let mut replacement = vec![];
1035 let mut fixed_crate_name = false;
1036 // Accept `extern crate name-like-this` for better diagnostics.
1037 let dash = token::BinOp(token::BinOpToken::Minus);
1038 if self.token == dash {
1039 // Do not include `-` as part of the expected tokens list.
1040 while self.eat(&dash) {
1041 fixed_crate_name = true;
1042 replacement.push((self.prev_token.span, "_".to_string()));
1043 idents.push(self.parse_ident()?);
1044 }
1045 }
1046 if fixed_crate_name {
1047 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
1048 let mut fixed_name = ident.name.to_string();
1049 for part in idents {
1050 fixed_name.push_str(&format!("_{}", part.name));
1051 }
1052 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
1053
1054 self.struct_span_err(fixed_name_sp, error_msg)
1055 .span_label(fixed_name_sp, "dash-separated idents are not valid")
1056 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
1057 .emit();
1058 }
1059 Ok(ident)
1060 }
1061
1062 /// Parses `extern` for foreign ABIs modules.
1063 ///
1064 /// `extern` is expected to have been consumed before calling this method.
1065 ///
1066 /// # Examples
1067 ///
1068 /// ```ignore (only-for-syntax-highlight)
1069 /// extern "C" {}
1070 /// extern {}
1071 /// ```
1072 fn parse_item_foreign_mod(
1073 &mut self,
1074 attrs: &mut AttrVec,
1075 mut unsafety: Unsafe,
1076 ) -> PResult<'a, ItemInfo> {
1077 let abi = self.parse_abi(); // ABI?
1078 if unsafety == Unsafe::No
1079 && self.token.is_keyword(kw::Unsafe)
1080 && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
1081 {
1082 let mut err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err();
1083 err.emit();
1084 unsafety = Unsafe::Yes(self.token.span);
1085 self.eat_keyword(kw::Unsafe);
1086 }
1087 let module = ast::ForeignMod {
1088 unsafety,
1089 abi,
1090 items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
1091 };
1092 Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1093 }
1094
1095 /// Parses a foreign item (one in an `extern { ... }` block).
1096 pub fn parse_foreign_item(
1097 &mut self,
1098 force_collect: ForceCollect,
1099 ) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
1100 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: false };
1101 Ok(self.parse_item_(fn_parse_mode, force_collect)?.map(
1102 |Item { attrs, id, span, vis, ident, kind, tokens }| {
1103 let kind = match ForeignItemKind::try_from(kind) {
1104 Ok(kind) => kind,
1105 Err(kind) => match kind {
1106 ItemKind::Const(_, a, b) => {
1107 self.error_on_foreign_const(span, ident);
1108 ForeignItemKind::Static(a, Mutability::Not, b)
1109 }
1110 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
1111 },
1112 };
1113 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
1114 },
1115 ))
1116 }
1117
1118 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
1119 let span = self.sess.source_map().guess_head_span(span);
1120 let descr = kind.descr();
1121 self.struct_span_err(span, &format!("{descr} is not supported in {ctx}"))
1122 .help(&format!("consider moving the {descr} out to a nearby module scope"))
1123 .emit();
1124 None
1125 }
1126
1127 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
1128 self.struct_span_err(ident.span, "extern items cannot be `const`")
1129 .span_suggestion(
1130 span.with_hi(ident.span.lo()),
1131 "try using a static value",
1132 "static ",
1133 Applicability::MachineApplicable,
1134 )
1135 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
1136 .emit();
1137 }
1138
1139 fn is_unsafe_foreign_mod(&self) -> bool {
1140 self.token.is_keyword(kw::Unsafe)
1141 && self.is_keyword_ahead(1, &[kw::Extern])
1142 && self.look_ahead(
1143 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
1144 |t| t.kind == token::OpenDelim(Delimiter::Brace),
1145 )
1146 }
1147
1148 fn is_static_global(&mut self) -> bool {
1149 if self.check_keyword(kw::Static) {
1150 // Check if this could be a closure.
1151 !self.look_ahead(1, |token| {
1152 if token.is_keyword(kw::Move) {
1153 return true;
1154 }
1155 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
1156 })
1157 } else {
1158 false
1159 }
1160 }
1161
1162 /// Recover on `const mut` with `const` already eaten.
1163 fn recover_const_mut(&mut self, const_span: Span) {
1164 if self.eat_keyword(kw::Mut) {
1165 let span = self.prev_token.span;
1166 self.struct_span_err(span, "const globals cannot be mutable")
1167 .span_label(span, "cannot be mutable")
1168 .span_suggestion(
1169 const_span,
1170 "you might want to declare a static instead",
1171 "static",
1172 Applicability::MaybeIncorrect,
1173 )
1174 .emit();
1175 } else if self.eat_keyword(kw::Let) {
1176 let span = self.prev_token.span;
1177 self.struct_span_err(const_span.to(span), "`const` and `let` are mutually exclusive")
1178 .span_suggestion(
1179 const_span.to(span),
1180 "remove `let`",
1181 "const",
1182 Applicability::MaybeIncorrect,
1183 )
1184 .emit();
1185 }
1186 }
1187
1188 /// Recover on `const impl` with `const` already eaten.
1189 fn recover_const_impl(
1190 &mut self,
1191 const_span: Span,
1192 attrs: &mut AttrVec,
1193 defaultness: Defaultness,
1194 ) -> PResult<'a, ItemInfo> {
1195 let impl_span = self.token.span;
1196 let mut err = self.expected_ident_found();
1197
1198 // Only try to recover if this is implementing a trait for a type
1199 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1200 Ok(impl_info) => impl_info,
1201 Err(recovery_error) => {
1202 // Recovery failed, raise the "expected identifier" error
1203 recovery_error.cancel();
1204 return Err(err);
1205 }
1206 };
1207
1208 match impl_info.1 {
1209 ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
1210 *constness = Const::Yes(const_span);
1211
1212 let before_trait = trai.path.span.shrink_to_lo();
1213 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1214 err.multipart_suggestion(
1215 "you might have meant to write a const trait impl",
1216 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1217 Applicability::MaybeIncorrect,
1218 )
1219 .emit();
1220 }
1221 ItemKind::Impl { .. } => return Err(err),
1222 _ => unreachable!(),
1223 }
1224
1225 Ok(impl_info)
1226 }
1227
1228 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1229 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1230 ///
1231 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1232 fn parse_item_global(
1233 &mut self,
1234 m: Option<Mutability>,
1235 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1236 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1237
1238 // Parse the type of a `const` or `static mut?` item.
1239 // That is, the `":" $ty` fragment.
1240 let ty = match (self.eat(&token::Colon), self.check(&token::Eq) | self.check(&token::Semi))
1241 {
1242 // If there wasn't a `:` or the colon was followed by a `=` or `;` recover a missing type.
1243 (true, false) => self.parse_ty()?,
1244 (colon, _) => self.recover_missing_const_type(colon, m),
1245 };
1246
1247 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1248 self.expect_semi()?;
1249 Ok((id, ty, expr))
1250 }
1251
1252 /// We were supposed to parse `":" $ty` but the `:` or the type was missing.
1253 /// This means that the type is missing.
1254 fn recover_missing_const_type(&mut self, colon_present: bool, m: Option<Mutability>) -> P<Ty> {
1255 // Construct the error and stash it away with the hope
1256 // that typeck will later enrich the error with a type.
1257 let kind = match m {
1258 Some(Mutability::Mut) => "static mut",
1259 Some(Mutability::Not) => "static",
1260 None => "const",
1261 };
1262
1263 let colon = match colon_present {
1264 true => "",
1265 false => ":",
1266 };
1267
1268 let span = self.prev_token.span.shrink_to_hi();
1269 let mut err = self.struct_span_err(span, &format!("missing type for `{kind}` item"));
1270 err.span_suggestion(
1271 span,
1272 "provide a type for the item",
1273 format!("{colon} <type>"),
1274 Applicability::HasPlaceholders,
1275 );
1276 err.stash(span, StashKey::ItemNoType);
1277
1278 // The user intended that the type be inferred,
1279 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1280 P(Ty { kind: TyKind::Infer, span, id: ast::DUMMY_NODE_ID, tokens: None })
1281 }
1282
1283 /// Parses an enum declaration.
1284 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1285 if self.token.is_keyword(kw::Struct) {
1286 let mut err = self.struct_span_err(
1287 self.prev_token.span.to(self.token.span),
1288 "`enum` and `struct` are mutually exclusive",
1289 );
1290 err.span_suggestion(
1291 self.prev_token.span.to(self.token.span),
1292 "replace `enum struct` with",
1293 "enum",
1294 Applicability::MachineApplicable,
1295 );
1296 if self.look_ahead(1, |t| t.is_ident()) {
1297 self.bump();
1298 err.emit();
1299 } else {
1300 return Err(err);
1301 }
1302 }
1303
1304 let id = self.parse_ident()?;
1305 let mut generics = self.parse_generics()?;
1306 generics.where_clause = self.parse_where_clause()?;
1307
1308 let (variants, _) = self
1309 .parse_delim_comma_seq(Delimiter::Brace, |p| p.parse_enum_variant())
1310 .map_err(|e| {
1311 self.recover_stmt();
1312 e
1313 })?;
1314
1315 let enum_definition = EnumDef { variants: variants.into_iter().flatten().collect() };
1316 Ok((id, ItemKind::Enum(enum_definition, generics)))
1317 }
1318
1319 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1320 let variant_attrs = self.parse_outer_attributes()?;
1321 self.collect_tokens_trailing_token(
1322 variant_attrs,
1323 ForceCollect::No,
1324 |this, variant_attrs| {
1325 let vlo = this.token.span;
1326
1327 let vis = this.parse_visibility(FollowedByType::No)?;
1328 if !this.recover_nested_adt_item(kw::Enum)? {
1329 return Ok((None, TrailingToken::None));
1330 }
1331 let ident = this.parse_field_ident("enum", vlo)?;
1332
1333 let struct_def = if this.check(&token::OpenDelim(Delimiter::Brace)) {
1334 // Parse a struct variant.
1335 let (fields, recovered) = this.parse_record_struct_body("struct", false)?;
1336 VariantData::Struct(fields, recovered)
1337 } else if this.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1338 VariantData::Tuple(this.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1339 } else {
1340 VariantData::Unit(DUMMY_NODE_ID)
1341 };
1342
1343 let disr_expr =
1344 if this.eat(&token::Eq) { Some(this.parse_anon_const_expr()?) } else { None };
1345
1346 let vr = ast::Variant {
1347 ident,
1348 vis,
1349 id: DUMMY_NODE_ID,
1350 attrs: variant_attrs,
1351 data: struct_def,
1352 disr_expr,
1353 span: vlo.to(this.prev_token.span),
1354 is_placeholder: false,
1355 };
1356
1357 Ok((Some(vr), TrailingToken::MaybeComma))
1358 },
1359 )
1360 }
1361
1362 /// Parses `struct Foo { ... }`.
1363 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1364 let class_name = self.parse_ident()?;
1365
1366 let mut generics = self.parse_generics()?;
1367
1368 // There is a special case worth noting here, as reported in issue #17904.
1369 // If we are parsing a tuple struct it is the case that the where clause
1370 // should follow the field list. Like so:
1371 //
1372 // struct Foo<T>(T) where T: Copy;
1373 //
1374 // If we are parsing a normal record-style struct it is the case
1375 // that the where clause comes before the body, and after the generics.
1376 // So if we look ahead and see a brace or a where-clause we begin
1377 // parsing a record style struct.
1378 //
1379 // Otherwise if we look ahead and see a paren we parse a tuple-style
1380 // struct.
1381
1382 let vdata = if self.token.is_keyword(kw::Where) {
1383 generics.where_clause = self.parse_where_clause()?;
1384 if self.eat(&token::Semi) {
1385 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1386 VariantData::Unit(DUMMY_NODE_ID)
1387 } else {
1388 // If we see: `struct Foo<T> where T: Copy { ... }`
1389 let (fields, recovered) =
1390 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1391 VariantData::Struct(fields, recovered)
1392 }
1393 // No `where` so: `struct Foo<T>;`
1394 } else if self.eat(&token::Semi) {
1395 VariantData::Unit(DUMMY_NODE_ID)
1396 // Record-style struct definition
1397 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1398 let (fields, recovered) =
1399 self.parse_record_struct_body("struct", generics.where_clause.has_where_token)?;
1400 VariantData::Struct(fields, recovered)
1401 // Tuple-style struct definition with optional where-clause.
1402 } else if self.token == token::OpenDelim(Delimiter::Parenthesis) {
1403 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1404 generics.where_clause = self.parse_where_clause()?;
1405 self.expect_semi()?;
1406 body
1407 } else {
1408 let token_str = super::token_descr(&self.token);
1409 let msg = &format!(
1410 "expected `where`, `{{`, `(`, or `;` after struct name, found {token_str}"
1411 );
1412 let mut err = self.struct_span_err(self.token.span, msg);
1413 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1414 return Err(err);
1415 };
1416
1417 Ok((class_name, ItemKind::Struct(vdata, generics)))
1418 }
1419
1420 /// Parses `union Foo { ... }`.
1421 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1422 let class_name = self.parse_ident()?;
1423
1424 let mut generics = self.parse_generics()?;
1425
1426 let vdata = if self.token.is_keyword(kw::Where) {
1427 generics.where_clause = self.parse_where_clause()?;
1428 let (fields, recovered) =
1429 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1430 VariantData::Struct(fields, recovered)
1431 } else if self.token == token::OpenDelim(Delimiter::Brace) {
1432 let (fields, recovered) =
1433 self.parse_record_struct_body("union", generics.where_clause.has_where_token)?;
1434 VariantData::Struct(fields, recovered)
1435 } else {
1436 let token_str = super::token_descr(&self.token);
1437 let msg = &format!("expected `where` or `{{` after union name, found {token_str}");
1438 let mut err = self.struct_span_err(self.token.span, msg);
1439 err.span_label(self.token.span, "expected `where` or `{` after union name");
1440 return Err(err);
1441 };
1442
1443 Ok((class_name, ItemKind::Union(vdata, generics)))
1444 }
1445
1446 fn parse_record_struct_body(
1447 &mut self,
1448 adt_ty: &str,
1449 parsed_where: bool,
1450 ) -> PResult<'a, (Vec<FieldDef>, /* recovered */ bool)> {
1451 let mut fields = Vec::new();
1452 let mut recovered = false;
1453 if self.eat(&token::OpenDelim(Delimiter::Brace)) {
1454 while self.token != token::CloseDelim(Delimiter::Brace) {
1455 let field = self.parse_field_def(adt_ty).map_err(|e| {
1456 self.consume_block(Delimiter::Brace, ConsumeClosingDelim::No);
1457 recovered = true;
1458 e
1459 });
1460 match field {
1461 Ok(field) => fields.push(field),
1462 Err(mut err) => {
1463 err.emit();
1464 break;
1465 }
1466 }
1467 }
1468 self.eat(&token::CloseDelim(Delimiter::Brace));
1469 } else {
1470 let token_str = super::token_descr(&self.token);
1471 let msg = &format!(
1472 "expected {}`{{` after struct name, found {}",
1473 if parsed_where { "" } else { "`where`, or " },
1474 token_str
1475 );
1476 let mut err = self.struct_span_err(self.token.span, msg);
1477 err.span_label(
1478 self.token.span,
1479 format!(
1480 "expected {}`{{` after struct name",
1481 if parsed_where { "" } else { "`where`, or " }
1482 ),
1483 );
1484 return Err(err);
1485 }
1486
1487 Ok((fields, recovered))
1488 }
1489
1490 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<FieldDef>> {
1491 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1492 // Unit like structs are handled in parse_item_struct function
1493 self.parse_paren_comma_seq(|p| {
1494 let attrs = p.parse_outer_attributes()?;
1495 p.collect_tokens_trailing_token(attrs, ForceCollect::No, |p, attrs| {
1496 let lo = p.token.span;
1497 let vis = p.parse_visibility(FollowedByType::Yes)?;
1498 let ty = p.parse_ty()?;
1499
1500 Ok((
1501 FieldDef {
1502 span: lo.to(ty.span),
1503 vis,
1504 ident: None,
1505 id: DUMMY_NODE_ID,
1506 ty,
1507 attrs,
1508 is_placeholder: false,
1509 },
1510 TrailingToken::MaybeComma,
1511 ))
1512 })
1513 })
1514 .map(|(r, _)| r)
1515 }
1516
1517 /// Parses an element of a struct declaration.
1518 fn parse_field_def(&mut self, adt_ty: &str) -> PResult<'a, FieldDef> {
1519 let attrs = self.parse_outer_attributes()?;
1520 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1521 let lo = this.token.span;
1522 let vis = this.parse_visibility(FollowedByType::No)?;
1523 Ok((this.parse_single_struct_field(adt_ty, lo, vis, attrs)?, TrailingToken::None))
1524 })
1525 }
1526
1527 /// Parses a structure field declaration.
1528 fn parse_single_struct_field(
1529 &mut self,
1530 adt_ty: &str,
1531 lo: Span,
1532 vis: Visibility,
1533 attrs: AttrVec,
1534 ) -> PResult<'a, FieldDef> {
1535 let mut seen_comma: bool = false;
1536 let a_var = self.parse_name_and_ty(adt_ty, lo, vis, attrs)?;
1537 if self.token == token::Comma {
1538 seen_comma = true;
1539 }
1540 if self.eat(&token::Semi) {
1541 let sp = self.prev_token.span;
1542 let mut err = self.struct_span_err(sp, format!("{adt_ty} fields are separated by `,`"));
1543 err.span_suggestion_short(
1544 sp,
1545 "replace `;` with `,`",
1546 ",",
1547 Applicability::MachineApplicable,
1548 );
1549 return Err(err);
1550 }
1551 match self.token.kind {
1552 token::Comma => {
1553 self.bump();
1554 }
1555 token::CloseDelim(Delimiter::Brace) => {}
1556 token::DocComment(..) => {
1557 let previous_span = self.prev_token.span;
1558 let mut err = self.span_err(self.token.span, Error::UselessDocComment);
1559 self.bump(); // consume the doc comment
1560 let comma_after_doc_seen = self.eat(&token::Comma);
1561 // `seen_comma` is always false, because we are inside doc block
1562 // condition is here to make code more readable
1563 if !seen_comma && comma_after_doc_seen {
1564 seen_comma = true;
1565 }
1566 if comma_after_doc_seen || self.token == token::CloseDelim(Delimiter::Brace) {
1567 err.emit();
1568 } else {
1569 if !seen_comma {
1570 let sp = self.sess.source_map().next_point(previous_span);
1571 err.span_suggestion(
1572 sp,
1573 "missing comma here",
1574 ",",
1575 Applicability::MachineApplicable,
1576 );
1577 }
1578 return Err(err);
1579 }
1580 }
1581 _ => {
1582 let sp = self.prev_token.span.shrink_to_hi();
1583 let mut err = self.struct_span_err(
1584 sp,
1585 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1586 );
1587
1588 // Try to recover extra trailing angle brackets
1589 let mut recovered = false;
1590 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1591 if let Some(last_segment) = segments.last() {
1592 recovered = self.check_trailing_angle_brackets(
1593 last_segment,
1594 &[&token::Comma, &token::CloseDelim(Delimiter::Brace)],
1595 );
1596 if recovered {
1597 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1598 // after the comma
1599 self.eat(&token::Comma);
1600 // `check_trailing_angle_brackets` already emitted a nicer error
1601 // NOTE(eddyb) this was `.cancel()`, but `err`
1602 // gets returned, so we can't fully defuse it.
1603 err.delay_as_bug();
1604 }
1605 }
1606 }
1607
1608 if self.token.is_ident()
1609 || (self.token.kind == TokenKind::Pound
1610 && (self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Bracket))))
1611 {
1612 // This is likely another field, TokenKind::Pound is used for `#[..]` attribute for next field,
1613 // emit the diagnostic and keep going
1614 err.span_suggestion(
1615 sp,
1616 "try adding a comma",
1617 ",",
1618 Applicability::MachineApplicable,
1619 );
1620 err.emit();
1621 recovered = true;
1622 }
1623
1624 if recovered {
1625 // Make sure an error was emitted (either by recovering an angle bracket,
1626 // or by finding an identifier as the next token), since we're
1627 // going to continue parsing
1628 assert!(self.sess.span_diagnostic.has_errors().is_some());
1629 } else {
1630 return Err(err);
1631 }
1632 }
1633 }
1634 Ok(a_var)
1635 }
1636
1637 fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> {
1638 if let Err(mut err) = self.expect(&token::Colon) {
1639 let sm = self.sess.source_map();
1640 let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start());
1641 let semi_typo = self.token.kind == token::Semi
1642 && self.look_ahead(1, |t| {
1643 t.is_path_start()
1644 // We check that we are in a situation like `foo; bar` to avoid bad suggestions
1645 // when there's no type and `;` was used instead of a comma.
1646 && match (sm.lookup_line(self.token.span.hi()), sm.lookup_line(t.span.lo())) {
1647 (Ok(l), Ok(r)) => l.line == r.line,
1648 _ => true,
1649 }
1650 });
1651 if eq_typo || semi_typo {
1652 self.bump();
1653 // Gracefully handle small typos.
1654 err.span_suggestion_short(
1655 self.prev_token.span,
1656 "field names and their types are separated with `:`",
1657 ":",
1658 Applicability::MachineApplicable,
1659 );
1660 err.emit();
1661 } else {
1662 return Err(err);
1663 }
1664 }
1665 Ok(())
1666 }
1667
1668 /// Parses a structure field.
1669 fn parse_name_and_ty(
1670 &mut self,
1671 adt_ty: &str,
1672 lo: Span,
1673 vis: Visibility,
1674 attrs: AttrVec,
1675 ) -> PResult<'a, FieldDef> {
1676 let name = self.parse_field_ident(adt_ty, lo)?;
1677 self.expect_field_ty_separator()?;
1678 let ty = self.parse_ty()?;
1679 if self.token.kind == token::Colon && self.look_ahead(1, |tok| tok.kind != token::Colon) {
1680 self.struct_span_err(self.token.span, "found single colon in a struct field type path")
1681 .span_suggestion_verbose(
1682 self.token.span,
1683 "write a path separator here",
1684 "::",
1685 Applicability::MaybeIncorrect,
1686 )
1687 .emit();
1688 }
1689 if self.token.kind == token::Eq {
1690 self.bump();
1691 let const_expr = self.parse_anon_const_expr()?;
1692 let sp = ty.span.shrink_to_hi().to(const_expr.value.span);
1693 self.struct_span_err(sp, "default values on `struct` fields aren't supported")
1694 .span_suggestion(
1695 sp,
1696 "remove this unsupported default value",
1697 "",
1698 Applicability::MachineApplicable,
1699 )
1700 .emit();
1701 }
1702 Ok(FieldDef {
1703 span: lo.to(self.prev_token.span),
1704 ident: Some(name),
1705 vis,
1706 id: DUMMY_NODE_ID,
1707 ty,
1708 attrs,
1709 is_placeholder: false,
1710 })
1711 }
1712
1713 /// Parses a field identifier. Specialized version of `parse_ident_common`
1714 /// for better diagnostics and suggestions.
1715 fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> {
1716 let (ident, is_raw) = self.ident_or_err()?;
1717 if !is_raw && ident.is_reserved() {
1718 let err = if self.check_fn_front_matter(false) {
1719 let inherited_vis = Visibility {
1720 span: rustc_span::DUMMY_SP,
1721 kind: VisibilityKind::Inherited,
1722 tokens: None,
1723 };
1724 // We use `parse_fn` to get a span for the function
1725 let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true };
1726 if let Err(mut db) =
1727 self.parse_fn(&mut AttrVec::new(), fn_parse_mode, lo, &inherited_vis)
1728 {
1729 db.delay_as_bug();
1730 }
1731 let mut err = self.struct_span_err(
1732 lo.to(self.prev_token.span),
1733 &format!("functions are not allowed in {adt_ty} definitions"),
1734 );
1735 err.help("unlike in C++, Java, and C#, functions are declared in `impl` blocks");
1736 err.help("see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information");
1737 err
1738 } else {
1739 self.expected_ident_found()
1740 };
1741 return Err(err);
1742 }
1743 self.bump();
1744 Ok(ident)
1745 }
1746
1747 /// Parses a declarative macro 2.0 definition.
1748 /// The `macro` keyword has already been parsed.
1749 /// ```ebnf
1750 /// MacBody = "{" TOKEN_STREAM "}" ;
1751 /// MacParams = "(" TOKEN_STREAM ")" ;
1752 /// DeclMac = "macro" Ident MacParams? MacBody ;
1753 /// ```
1754 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1755 let ident = self.parse_ident()?;
1756 let body = if self.check(&token::OpenDelim(Delimiter::Brace)) {
1757 self.parse_mac_args()? // `MacBody`
1758 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1759 let params = self.parse_token_tree(); // `MacParams`
1760 let pspan = params.span();
1761 if !self.check(&token::OpenDelim(Delimiter::Brace)) {
1762 return self.unexpected();
1763 }
1764 let body = self.parse_token_tree(); // `MacBody`
1765 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1766 let bspan = body.span();
1767 let arrow = TokenTree::token_alone(token::FatArrow, pspan.between(bspan)); // `=>`
1768 let tokens = TokenStream::new(vec![params, arrow, body]);
1769 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1770 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1771 } else {
1772 return self.unexpected();
1773 };
1774
1775 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1776 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1777 }
1778
1779 /// Is this a possibly malformed start of a `macro_rules! foo` item definition?
1780 fn is_macro_rules_item(&mut self) -> IsMacroRulesItem {
1781 if self.check_keyword(kw::MacroRules) {
1782 let macro_rules_span = self.token.span;
1783
1784 if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) {
1785 return IsMacroRulesItem::Yes { has_bang: true };
1786 } else if self.look_ahead(1, |t| (t.is_ident())) {
1787 // macro_rules foo
1788 self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`")
1789 .span_suggestion(
1790 macro_rules_span,
1791 "add a `!`",
1792 "macro_rules!",
1793 Applicability::MachineApplicable,
1794 )
1795 .emit();
1796
1797 return IsMacroRulesItem::Yes { has_bang: false };
1798 }
1799 }
1800
1801 IsMacroRulesItem::No
1802 }
1803
1804 /// Parses a `macro_rules! foo { ... }` declarative macro.
1805 fn parse_item_macro_rules(
1806 &mut self,
1807 vis: &Visibility,
1808 has_bang: bool,
1809 ) -> PResult<'a, ItemInfo> {
1810 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1811
1812 if has_bang {
1813 self.expect(&token::Not)?; // `!`
1814 }
1815 let ident = self.parse_ident()?;
1816
1817 if self.eat(&token::Not) {
1818 // Handle macro_rules! foo!
1819 let span = self.prev_token.span;
1820 self.struct_span_err(span, "macro names aren't followed by a `!`")
1821 .span_suggestion(span, "remove the `!`", "", Applicability::MachineApplicable)
1822 .emit();
1823 }
1824
1825 let body = self.parse_mac_args()?;
1826 self.eat_semi_for_macro_if_needed(&body);
1827 self.complain_if_pub_macro(vis, true);
1828
1829 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1830 }
1831
1832 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1833 /// If that's not the case, emit an error.
1834 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1835 if let VisibilityKind::Inherited = vis.kind {
1836 return;
1837 }
1838
1839 let vstr = pprust::vis_to_string(vis);
1840 let vstr = vstr.trim_end();
1841 if macro_rules {
1842 let msg = format!("can't qualify macro_rules invocation with `{vstr}`");
1843 self.struct_span_err(vis.span, &msg)
1844 .span_suggestion(
1845 vis.span,
1846 "try exporting the macro",
1847 "#[macro_export]",
1848 Applicability::MaybeIncorrect, // speculative
1849 )
1850 .emit();
1851 } else {
1852 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1853 .span_suggestion(
1854 vis.span,
1855 "remove the visibility",
1856 "",
1857 Applicability::MachineApplicable,
1858 )
1859 .help(&format!("try adjusting the macro to put `{vstr}` inside the invocation"))
1860 .emit();
1861 }
1862 }
1863
1864 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1865 if args.need_semicolon() && !self.eat(&token::Semi) {
1866 self.report_invalid_macro_expansion_item(args);
1867 }
1868 }
1869
1870 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1871 let span = args.span().expect("undelimited macro call");
1872 let mut err = self.struct_span_err(
1873 span,
1874 "macros that expand to items must be delimited with braces or followed by a semicolon",
1875 );
1876 // FIXME: This will make us not emit the help even for declarative
1877 // macros within the same crate (that we can fix), which is sad.
1878 if !span.from_expansion() {
1879 if self.unclosed_delims.is_empty() {
1880 let DelimSpan { open, close } = match args {
1881 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1882 MacArgs::Delimited(dspan, ..) => *dspan,
1883 };
1884 err.multipart_suggestion(
1885 "change the delimiters to curly braces",
1886 vec![(open, "{".to_string()), (close, '}'.to_string())],
1887 Applicability::MaybeIncorrect,
1888 );
1889 } else {
1890 err.span_suggestion(
1891 span,
1892 "change the delimiters to curly braces",
1893 " { /* items */ }",
1894 Applicability::HasPlaceholders,
1895 );
1896 }
1897 err.span_suggestion(
1898 span.shrink_to_hi(),
1899 "add a semicolon",
1900 ';',
1901 Applicability::MaybeIncorrect,
1902 );
1903 }
1904 err.emit();
1905 }
1906
1907 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1908 /// it is, we try to parse the item and report error about nested types.
1909 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1910 if (self.token.is_keyword(kw::Enum)
1911 || self.token.is_keyword(kw::Struct)
1912 || self.token.is_keyword(kw::Union))
1913 && self.look_ahead(1, |t| t.is_ident())
1914 {
1915 let kw_token = self.token.clone();
1916 let kw_str = pprust::token_to_string(&kw_token);
1917 let item = self.parse_item(ForceCollect::No)?;
1918
1919 self.struct_span_err(
1920 kw_token.span,
1921 &format!("`{kw_str}` definition cannot be nested inside `{keyword}`"),
1922 )
1923 .span_suggestion(
1924 item.unwrap().span,
1925 &format!("consider creating a new `{kw_str}` definition instead of nesting"),
1926 "",
1927 Applicability::MaybeIncorrect,
1928 )
1929 .emit();
1930 // We successfully parsed the item but we must inform the caller about nested problem.
1931 return Ok(false);
1932 }
1933 Ok(true)
1934 }
1935 }
1936
1937 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1938 ///
1939 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1940 ///
1941 /// This function pointer accepts an edition, because in edition 2015, trait declarations
1942 /// were allowed to omit parameter names. In 2018, they became required.
1943 type ReqName = fn(Edition) -> bool;
1944
1945 /// Parsing configuration for functions.
1946 ///
1947 /// The syntax of function items is slightly different within trait definitions,
1948 /// impl blocks, and modules. It is still parsed using the same code, just with
1949 /// different flags set, so that even when the input is wrong and produces a parse
1950 /// error, it still gets into the AST and the rest of the parser and
1951 /// type checker can run.
1952 #[derive(Clone, Copy)]
1953 pub(crate) struct FnParseMode {
1954 /// A function pointer that decides if, per-parameter `p`, `p` must have a
1955 /// pattern or just a type. This field affects parsing of the parameters list.
1956 ///
1957 /// ```text
1958 /// fn foo(alef: A) -> X { X::new() }
1959 /// -----^^ affects parsing this part of the function signature
1960 /// |
1961 /// if req_name returns false, then this name is optional
1962 ///
1963 /// fn bar(A) -> X;
1964 /// ^
1965 /// |
1966 /// if req_name returns true, this is an error
1967 /// ```
1968 ///
1969 /// Calling this function pointer should only return false if:
1970 ///
1971 /// * The item is being parsed inside of a trait definition.
1972 /// Within an impl block or a module, it should always evaluate
1973 /// to true.
1974 /// * The span is from Edition 2015. In particular, you can get a
1975 /// 2015 span inside a 2021 crate using macros.
1976 pub req_name: ReqName,
1977 /// If this flag is set to `true`, then plain, semicolon-terminated function
1978 /// prototypes are not allowed here.
1979 ///
1980 /// ```text
1981 /// fn foo(alef: A) -> X { X::new() }
1982 /// ^^^^^^^^^^^^
1983 /// |
1984 /// this is always allowed
1985 ///
1986 /// fn bar(alef: A, bet: B) -> X;
1987 /// ^
1988 /// |
1989 /// if req_body is set to true, this is an error
1990 /// ```
1991 ///
1992 /// This field should only be set to false if the item is inside of a trait
1993 /// definition or extern block. Within an impl block or a module, it should
1994 /// always be set to true.
1995 pub req_body: bool,
1996 }
1997
1998 /// Parsing of functions and methods.
1999 impl<'a> Parser<'a> {
2000 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
2001 fn parse_fn(
2002 &mut self,
2003 attrs: &mut AttrVec,
2004 fn_parse_mode: FnParseMode,
2005 sig_lo: Span,
2006 vis: &Visibility,
2007 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
2008 let header = self.parse_fn_front_matter(vis)?; // `const ... fn`
2009 let ident = self.parse_ident()?; // `foo`
2010 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
2011 let decl =
2012 self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
2013 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
2014
2015 let mut sig_hi = self.prev_token.span;
2016 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`.
2017 let fn_sig_span = sig_lo.to(sig_hi);
2018 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
2019 }
2020
2021 /// Parse the "body" of a function.
2022 /// This can either be `;` when there's no body,
2023 /// or e.g. a block when the function is a provided one.
2024 fn parse_fn_body(
2025 &mut self,
2026 attrs: &mut AttrVec,
2027 ident: &Ident,
2028 sig_hi: &mut Span,
2029 req_body: bool,
2030 ) -> PResult<'a, Option<P<Block>>> {
2031 let has_semi = if req_body {
2032 self.token.kind == TokenKind::Semi
2033 } else {
2034 // Only include `;` in list of expected tokens if body is not required
2035 self.check(&TokenKind::Semi)
2036 };
2037 let (inner_attrs, body) = if has_semi {
2038 // Include the trailing semicolon in the span of the signature
2039 self.expect_semi()?;
2040 *sig_hi = self.prev_token.span;
2041 (AttrVec::new(), None)
2042 } else if self.check(&token::OpenDelim(Delimiter::Brace)) || self.token.is_whole_block() {
2043 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
2044 } else if self.token.kind == token::Eq {
2045 // Recover `fn foo() = $expr;`.
2046 self.bump(); // `=`
2047 let eq_sp = self.prev_token.span;
2048 let _ = self.parse_expr()?;
2049 self.expect_semi()?; // `;`
2050 let span = eq_sp.to(self.prev_token.span);
2051 self.struct_span_err(span, "function body cannot be `= expression;`")
2052 .multipart_suggestion(
2053 "surround the expression with `{` and `}` instead of `=` and `;`",
2054 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
2055 Applicability::MachineApplicable,
2056 )
2057 .emit();
2058 (AttrVec::new(), Some(self.mk_block_err(span)))
2059 } else {
2060 let expected = if req_body {
2061 &[token::OpenDelim(Delimiter::Brace)][..]
2062 } else {
2063 &[token::Semi, token::OpenDelim(Delimiter::Brace)]
2064 };
2065 if let Err(mut err) = self.expected_one_of_not_found(&[], &expected) {
2066 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2067 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
2068 // the AST for typechecking.
2069 err.span_label(ident.span, "while parsing this `fn`");
2070 err.emit();
2071 } else {
2072 return Err(err);
2073 }
2074 }
2075 (AttrVec::new(), None)
2076 };
2077 attrs.extend(inner_attrs);
2078 Ok(body)
2079 }
2080
2081 /// Is the current token the start of an `FnHeader` / not a valid parse?
2082 ///
2083 /// `check_pub` adds additional `pub` to the checks in case users place it
2084 /// wrongly, can be used to ensure `pub` never comes after `default`.
2085 pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool {
2086 // We use an over-approximation here.
2087 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
2088 // `pub` is added in case users got confused with the ordering like `async pub fn`,
2089 // only if it wasn't preceded by `default` as `default pub` is invalid.
2090 let quals: &[Symbol] = if check_pub {
2091 &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2092 } else {
2093 &[kw::Const, kw::Async, kw::Unsafe, kw::Extern]
2094 };
2095 self.check_keyword(kw::Fn) // Definitely an `fn`.
2096 // `$qual fn` or `$qual $qual`:
2097 || quals.iter().any(|&kw| self.check_keyword(kw))
2098 && self.look_ahead(1, |t| {
2099 // `$qual fn`, e.g. `const fn` or `async fn`.
2100 t.is_keyword(kw::Fn)
2101 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
2102 || t.is_non_raw_ident_where(|i| quals.contains(&i.name)
2103 // Rule out 2015 `const async: T = val`.
2104 && i.is_reserved()
2105 // Rule out unsafe extern block.
2106 && !self.is_unsafe_foreign_mod())
2107 })
2108 // `extern ABI fn`
2109 || self.check_keyword(kw::Extern)
2110 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
2111 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
2112 }
2113
2114 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
2115 /// up to and including the `fn` keyword. The formal grammar is:
2116 ///
2117 /// ```text
2118 /// Extern = "extern" StringLit? ;
2119 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
2120 /// FnFrontMatter = FnQual "fn" ;
2121 /// ```
2122 ///
2123 /// `vis` represents the visibility that was already parsed, if any. Use
2124 /// `Visibility::Inherited` when no visibility is known.
2125 pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> {
2126 let sp_start = self.token.span;
2127 let constness = self.parse_constness();
2128
2129 let async_start_sp = self.token.span;
2130 let asyncness = self.parse_asyncness();
2131
2132 let unsafe_start_sp = self.token.span;
2133 let unsafety = self.parse_unsafety();
2134
2135 let ext_start_sp = self.token.span;
2136 let ext = self.parse_extern();
2137
2138 if let Async::Yes { span, .. } = asyncness {
2139 self.ban_async_in_2015(span);
2140 }
2141
2142 if !self.eat_keyword(kw::Fn) {
2143 // It is possible for `expect_one_of` to recover given the contents of
2144 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
2145 // account for this.
2146 match self.expect_one_of(&[], &[]) {
2147 Ok(true) => {}
2148 Ok(false) => unreachable!(),
2149 Err(mut err) => {
2150 // Qualifier keywords ordering check
2151 enum WrongKw {
2152 Duplicated(Span),
2153 Misplaced(Span),
2154 }
2155
2156 // This will allow the machine fix to directly place the keyword in the correct place or to indicate
2157 // that the keyword is already present and the second instance should be removed.
2158 let wrong_kw = if self.check_keyword(kw::Const) {
2159 match constness {
2160 Const::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2161 Const::No => Some(WrongKw::Misplaced(async_start_sp)),
2162 }
2163 } else if self.check_keyword(kw::Async) {
2164 match asyncness {
2165 Async::Yes { span, .. } => Some(WrongKw::Duplicated(span)),
2166 Async::No => Some(WrongKw::Misplaced(unsafe_start_sp)),
2167 }
2168 } else if self.check_keyword(kw::Unsafe) {
2169 match unsafety {
2170 Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)),
2171 Unsafe::No => Some(WrongKw::Misplaced(ext_start_sp)),
2172 }
2173 } else {
2174 None
2175 };
2176
2177 // The keyword is already present, suggest removal of the second instance
2178 if let Some(WrongKw::Duplicated(original_sp)) = wrong_kw {
2179 let original_kw = self
2180 .span_to_snippet(original_sp)
2181 .expect("Span extracted directly from keyword should always work");
2182
2183 err.span_suggestion(
2184 self.token.uninterpolated_span(),
2185 &format!("`{original_kw}` already used earlier, remove this one"),
2186 "",
2187 Applicability::MachineApplicable,
2188 )
2189 .span_note(original_sp, &format!("`{original_kw}` first seen here"));
2190 }
2191 // The keyword has not been seen yet, suggest correct placement in the function front matter
2192 else if let Some(WrongKw::Misplaced(correct_pos_sp)) = wrong_kw {
2193 let correct_pos_sp = correct_pos_sp.to(self.prev_token.span);
2194 if let Ok(current_qual) = self.span_to_snippet(correct_pos_sp) {
2195 let misplaced_qual_sp = self.token.uninterpolated_span();
2196 let misplaced_qual = self.span_to_snippet(misplaced_qual_sp).unwrap();
2197
2198 err.span_suggestion(
2199 correct_pos_sp.to(misplaced_qual_sp),
2200 &format!("`{misplaced_qual}` must come before `{current_qual}`"),
2201 format!("{misplaced_qual} {current_qual}"),
2202 Applicability::MachineApplicable,
2203 ).note("keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`");
2204 }
2205 }
2206 // Recover incorrect visibility order such as `async pub`
2207 else if self.check_keyword(kw::Pub) {
2208 let sp = sp_start.to(self.prev_token.span);
2209 if let Ok(snippet) = self.span_to_snippet(sp) {
2210 let current_vis = match self.parse_visibility(FollowedByType::No) {
2211 Ok(v) => v,
2212 Err(d) => {
2213 d.cancel();
2214 return Err(err);
2215 }
2216 };
2217 let vs = pprust::vis_to_string(&current_vis);
2218 let vs = vs.trim_end();
2219
2220 // There was no explicit visibility
2221 if matches!(orig_vis.kind, VisibilityKind::Inherited) {
2222 err.span_suggestion(
2223 sp_start.to(self.prev_token.span),
2224 &format!("visibility `{vs}` must come before `{snippet}`"),
2225 format!("{vs} {snippet}"),
2226 Applicability::MachineApplicable,
2227 );
2228 }
2229 // There was an explicit visibility
2230 else {
2231 err.span_suggestion(
2232 current_vis.span,
2233 "there is already a visibility modifier, remove one",
2234 "",
2235 Applicability::MachineApplicable,
2236 )
2237 .span_note(orig_vis.span, "explicit visibility first seen here");
2238 }
2239 }
2240 }
2241 return Err(err);
2242 }
2243 }
2244 }
2245
2246 Ok(FnHeader { constness, unsafety, asyncness, ext })
2247 }
2248
2249 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
2250 fn ban_async_in_2015(&self, span: Span) {
2251 if span.rust_2015() {
2252 let diag = self.diagnostic();
2253 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
2254 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
2255 .help_use_latest_edition()
2256 .emit();
2257 }
2258 }
2259
2260 /// Parses the parameter list and result type of a function declaration.
2261 pub(super) fn parse_fn_decl(
2262 &mut self,
2263 req_name: ReqName,
2264 ret_allow_plus: AllowPlus,
2265 recover_return_sign: RecoverReturnSign,
2266 ) -> PResult<'a, P<FnDecl>> {
2267 Ok(P(FnDecl {
2268 inputs: self.parse_fn_params(req_name)?,
2269 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
2270 }))
2271 }
2272
2273 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
2274 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
2275 let mut first_param = true;
2276 // Parse the arguments, starting out with `self` being allowed...
2277 let (mut params, _) = self.parse_paren_comma_seq(|p| {
2278 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
2279 e.emit();
2280 let lo = p.prev_token.span;
2281 // Skip every token until next possible arg or end.
2282 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]);
2283 // Create a placeholder argument for proper arg count (issue #34264).
2284 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
2285 });
2286 // ...now that we've parsed the first argument, `self` is no longer allowed.
2287 first_param = false;
2288 param
2289 })?;
2290 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
2291 self.deduplicate_recovered_params_names(&mut params);
2292 Ok(params)
2293 }
2294
2295 /// Parses a single function parameter.
2296 ///
2297 /// - `self` is syntactically allowed when `first_param` holds.
2298 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
2299 let lo = self.token.span;
2300 let attrs = self.parse_outer_attributes()?;
2301 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2302 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
2303 if let Some(mut param) = this.parse_self_param()? {
2304 param.attrs = attrs;
2305 let res = if first_param { Ok(param) } else { this.recover_bad_self_param(param) };
2306 return Ok((res?, TrailingToken::None));
2307 }
2308
2309 let is_name_required = match this.token.kind {
2310 token::DotDotDot => false,
2311 _ => req_name(this.token.span.edition()),
2312 };
2313 let (pat, ty) = if is_name_required || this.is_named_param() {
2314 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
2315
2316 let (pat, colon) = this.parse_fn_param_pat_colon()?;
2317 if !colon {
2318 let mut err = this.unexpected::<()>().unwrap_err();
2319 return if let Some(ident) =
2320 this.parameter_without_type(&mut err, pat, is_name_required, first_param)
2321 {
2322 err.emit();
2323 Ok((dummy_arg(ident), TrailingToken::None))
2324 } else {
2325 Err(err)
2326 };
2327 }
2328
2329 this.eat_incorrect_doc_comment_for_param_type();
2330 (pat, this.parse_ty_for_param()?)
2331 } else {
2332 debug!("parse_param_general ident_to_pat");
2333 let parser_snapshot_before_ty = this.create_snapshot_for_diagnostic();
2334 this.eat_incorrect_doc_comment_for_param_type();
2335 let mut ty = this.parse_ty_for_param();
2336 if ty.is_ok()
2337 && this.token != token::Comma
2338 && this.token != token::CloseDelim(Delimiter::Parenthesis)
2339 {
2340 // This wasn't actually a type, but a pattern looking like a type,
2341 // so we are going to rollback and re-parse for recovery.
2342 ty = this.unexpected();
2343 }
2344 match ty {
2345 Ok(ty) => {
2346 let ident = Ident::new(kw::Empty, this.prev_token.span);
2347 let bm = BindingAnnotation::NONE;
2348 let pat = this.mk_pat_ident(ty.span, bm, ident);
2349 (pat, ty)
2350 }
2351 // If this is a C-variadic argument and we hit an error, return the error.
2352 Err(err) if this.token == token::DotDotDot => return Err(err),
2353 // Recover from attempting to parse the argument as a type without pattern.
2354 Err(err) => {
2355 err.cancel();
2356 this.restore_snapshot(parser_snapshot_before_ty);
2357 this.recover_arg_parse()?
2358 }
2359 }
2360 };
2361
2362 let span = lo.to(this.prev_token.span);
2363
2364 Ok((
2365 Param { attrs, id: ast::DUMMY_NODE_ID, is_placeholder: false, pat, span, ty },
2366 TrailingToken::None,
2367 ))
2368 })
2369 }
2370
2371 /// Returns the parsed optional self parameter and whether a self shortcut was used.
2372 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
2373 // Extract an identifier *after* having confirmed that the token is one.
2374 let expect_self_ident = |this: &mut Self| match this.token.ident() {
2375 Some((ident, false)) => {
2376 this.bump();
2377 ident
2378 }
2379 _ => unreachable!(),
2380 };
2381 // Is `self` `n` tokens ahead?
2382 let is_isolated_self = |this: &Self, n| {
2383 this.is_keyword_ahead(n, &[kw::SelfLower])
2384 && this.look_ahead(n + 1, |t| t != &token::ModSep)
2385 };
2386 // Is `mut self` `n` tokens ahead?
2387 let is_isolated_mut_self =
2388 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
2389 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
2390 let parse_self_possibly_typed = |this: &mut Self, m| {
2391 let eself_ident = expect_self_ident(this);
2392 let eself_hi = this.prev_token.span;
2393 let eself = if this.eat(&token::Colon) {
2394 SelfKind::Explicit(this.parse_ty()?, m)
2395 } else {
2396 SelfKind::Value(m)
2397 };
2398 Ok((eself, eself_ident, eself_hi))
2399 };
2400 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
2401 let recover_self_ptr = |this: &mut Self| {
2402 let msg = "cannot pass `self` by raw pointer";
2403 let span = this.token.span;
2404 this.struct_span_err(span, msg).span_label(span, msg).emit();
2405
2406 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
2407 };
2408
2409 // Parse optional `self` parameter of a method.
2410 // Only a limited set of initial token sequences is considered `self` parameters; anything
2411 // else is parsed as a normal function parameter list, so some lookahead is required.
2412 let eself_lo = self.token.span;
2413 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
2414 token::BinOp(token::And) => {
2415 let eself = if is_isolated_self(self, 1) {
2416 // `&self`
2417 self.bump();
2418 SelfKind::Region(None, Mutability::Not)
2419 } else if is_isolated_mut_self(self, 1) {
2420 // `&mut self`
2421 self.bump();
2422 self.bump();
2423 SelfKind::Region(None, Mutability::Mut)
2424 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
2425 // `&'lt self`
2426 self.bump();
2427 let lt = self.expect_lifetime();
2428 SelfKind::Region(Some(lt), Mutability::Not)
2429 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
2430 // `&'lt mut self`
2431 self.bump();
2432 let lt = self.expect_lifetime();
2433 self.bump();
2434 SelfKind::Region(Some(lt), Mutability::Mut)
2435 } else {
2436 // `&not_self`
2437 return Ok(None);
2438 };
2439 (eself, expect_self_ident(self), self.prev_token.span)
2440 }
2441 // `*self`
2442 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
2443 self.bump();
2444 recover_self_ptr(self)?
2445 }
2446 // `*mut self` and `*const self`
2447 token::BinOp(token::Star)
2448 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
2449 {
2450 self.bump();
2451 self.bump();
2452 recover_self_ptr(self)?
2453 }
2454 // `self` and `self: TYPE`
2455 token::Ident(..) if is_isolated_self(self, 0) => {
2456 parse_self_possibly_typed(self, Mutability::Not)?
2457 }
2458 // `mut self` and `mut self: TYPE`
2459 token::Ident(..) if is_isolated_mut_self(self, 0) => {
2460 self.bump();
2461 parse_self_possibly_typed(self, Mutability::Mut)?
2462 }
2463 _ => return Ok(None),
2464 };
2465
2466 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
2467 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
2468 }
2469
2470 fn is_named_param(&self) -> bool {
2471 let offset = match self.token.kind {
2472 token::Interpolated(ref nt) => match **nt {
2473 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2474 _ => 0,
2475 },
2476 token::BinOp(token::And) | token::AndAnd => 1,
2477 _ if self.token.is_keyword(kw::Mut) => 1,
2478 _ => 0,
2479 };
2480
2481 self.look_ahead(offset, |t| t.is_ident())
2482 && self.look_ahead(offset + 1, |t| t == &token::Colon)
2483 }
2484
2485 fn recover_first_param(&mut self) -> &'static str {
2486 match self
2487 .parse_outer_attributes()
2488 .and_then(|_| self.parse_self_param())
2489 .map_err(|e| e.cancel())
2490 {
2491 Ok(Some(_)) => "method",
2492 _ => "function",
2493 }
2494 }
2495 }
2496
2497 enum IsMacroRulesItem {
2498 Yes { has_bang: bool },
2499 No,
2500 }