]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_parse/src/parser/item.rs
New upstream version 1.51.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::{FollowedByType, ForceCollect, Parser, PathStyle, TrailingToken};
4
5 use crate::{maybe_collect_tokens, maybe_whole};
6
7 use rustc_ast::ast::*;
8 use rustc_ast::ptr::P;
9 use rustc_ast::token::{self, TokenKind};
10 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
11 use rustc_ast::{self as ast, AttrVec, Attribute, DUMMY_NODE_ID};
12 use rustc_ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind};
13 use rustc_ast::{BindingMode, Block, FnDecl, FnSig, Param, SelfKind};
14 use rustc_ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData};
15 use rustc_ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind};
16 use rustc_ast::{MacArgs, MacCall, MacDelimiter};
17 use rustc_ast_pretty::pprust;
18 use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
19 use rustc_span::edition::{Edition, LATEST_STABLE_EDITION};
20 use rustc_span::source_map::{self, Span};
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22
23 use std::convert::TryFrom;
24 use std::mem;
25 use tracing::debug;
26
27 impl<'a> Parser<'a> {
28 /// Parses a source module as a crate. This is the main entry point for the parser.
29 pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
30 let lo = self.token.span;
31 let (module, attrs) = self.parse_mod(&token::Eof, Unsafe::No)?;
32 let span = lo.to(self.token.span);
33 let proc_macros = Vec::new(); // Filled in by `proc_macro_harness::inject()`.
34 Ok(ast::Crate { attrs, module, span, proc_macros })
35 }
36
37 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
38 fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
39 let unsafety = self.parse_unsafety();
40 self.expect_keyword(kw::Mod)?;
41 let id = self.parse_ident()?;
42 let (module, mut inner_attrs) = if self.eat(&token::Semi) {
43 (Mod { inner: Span::default(), unsafety, items: Vec::new(), inline: false }, Vec::new())
44 } else {
45 self.expect(&token::OpenDelim(token::Brace))?;
46 self.parse_mod(&token::CloseDelim(token::Brace), unsafety)?
47 };
48 attrs.append(&mut inner_attrs);
49 Ok((id, ItemKind::Mod(module)))
50 }
51
52 /// Parses the contents of a module (inner attributes followed by module items).
53 pub fn parse_mod(
54 &mut self,
55 term: &TokenKind,
56 unsafety: Unsafe,
57 ) -> PResult<'a, (Mod, Vec<Attribute>)> {
58 let lo = self.token.span;
59 let attrs = self.parse_inner_attributes()?;
60 let module = self.parse_mod_items(term, lo, unsafety)?;
61 Ok((module, attrs))
62 }
63
64 /// Given a termination token, parses all of the items in a module.
65 fn parse_mod_items(
66 &mut self,
67 term: &TokenKind,
68 inner_lo: Span,
69 unsafety: Unsafe,
70 ) -> PResult<'a, Mod> {
71 let mut items = vec![];
72 while let Some(item) = self.parse_item(ForceCollect::No)? {
73 items.push(item);
74 self.maybe_consume_incorrect_semicolon(&items);
75 }
76
77 if !self.eat(term) {
78 let token_str = super::token_descr(&self.token);
79 if !self.maybe_consume_incorrect_semicolon(&items) {
80 let msg = &format!("expected item, found {}", token_str);
81 let mut err = self.struct_span_err(self.token.span, msg);
82 err.span_label(self.token.span, "expected item");
83 return Err(err);
84 }
85 }
86
87 let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_token.span };
88
89 Ok(Mod { inner: inner_lo.to(hi), unsafety, items, inline: true })
90 }
91 }
92
93 pub(super) type ItemInfo = (Ident, ItemKind);
94
95 impl<'a> Parser<'a> {
96 pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<P<Item>>> {
97 self.parse_item_(|_| true, force_collect).map(|i| i.map(P))
98 }
99
100 fn parse_item_(
101 &mut self,
102 req_name: ReqName,
103 force_collect: ForceCollect,
104 ) -> PResult<'a, Option<Item>> {
105 let attrs = self.parse_outer_attributes()?;
106 self.parse_item_common(attrs, true, false, req_name, force_collect)
107 }
108
109 pub(super) fn parse_item_common(
110 &mut self,
111 mut attrs: Vec<Attribute>,
112 mac_allowed: bool,
113 attrs_allowed: bool,
114 req_name: ReqName,
115 force_collect: ForceCollect,
116 ) -> PResult<'a, Option<Item>> {
117 maybe_whole!(self, NtItem, |item| {
118 let mut item = item;
119 mem::swap(&mut item.attrs, &mut attrs);
120 item.attrs.extend(attrs);
121 Some(item.into_inner())
122 });
123
124 let mut unclosed_delims = vec![];
125 let item = maybe_collect_tokens!(self, force_collect, &attrs, |this: &mut Self| {
126 let item = this.parse_item_common_(attrs, mac_allowed, attrs_allowed, req_name);
127 unclosed_delims.append(&mut this.unclosed_delims);
128 Ok((item?, TrailingToken::None))
129 })?;
130
131 self.unclosed_delims.append(&mut unclosed_delims);
132 Ok(item)
133 }
134
135 fn parse_item_common_(
136 &mut self,
137 mut attrs: Vec<Attribute>,
138 mac_allowed: bool,
139 attrs_allowed: bool,
140 req_name: ReqName,
141 ) -> PResult<'a, Option<Item>> {
142 let lo = self.token.span;
143 let vis = self.parse_visibility(FollowedByType::No)?;
144 let mut def = self.parse_defaultness();
145 let kind = self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, req_name)?;
146 if let Some((ident, kind)) = kind {
147 self.error_on_unconsumed_default(def, &kind);
148 let span = lo.to(self.prev_token.span);
149 let id = DUMMY_NODE_ID;
150 let item = Item { ident, attrs, id, kind, vis, span, tokens: None };
151 return Ok(Some(item));
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 `{}` is not followed by an item", vs))
171 .span_label(vis.span, "the visibility")
172 .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs))
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 Vec<Attribute>,
201 macros_allowed: bool,
202 lo: Span,
203 vis: &Visibility,
204 def: &mut Defaultness,
205 req_name: ReqName,
206 ) -> PResult<'a, Option<ItemInfo>> {
207 let mut def = || mem::replace(def, Defaultness::Final);
208
209 let info = if self.eat_keyword(kw::Use) {
210 // USE ITEM
211 let tree = self.parse_use_tree()?;
212
213 // If wildcard or glob-like brace syntax doesn't have `;`,
214 // the user may not know `*` or `{}` should be the last.
215 if let Err(mut e) = self.expect_semi() {
216 match tree.kind {
217 UseTreeKind::Glob => {
218 e.note("the wildcard token must be last on the path").emit();
219 }
220 UseTreeKind::Nested(..) => {
221 e.note("glob-like brace syntax must be last on the path").emit();
222 }
223 _ => (),
224 }
225 return Err(e);
226 }
227
228 (Ident::invalid(), ItemKind::Use(P(tree)))
229 } else if self.check_fn_front_matter() {
230 // FUNCTION ITEM
231 let (ident, sig, generics, body) = self.parse_fn(attrs, req_name, lo)?;
232 (ident, ItemKind::Fn(box FnKind(def(), sig, generics, body)))
233 } else if self.eat_keyword(kw::Extern) {
234 if self.eat_keyword(kw::Crate) {
235 // EXTERN CRATE
236 self.parse_item_extern_crate()?
237 } else {
238 // EXTERN BLOCK
239 self.parse_item_foreign_mod(attrs, Unsafe::No)?
240 }
241 } else if self.is_unsafe_foreign_mod() {
242 // EXTERN BLOCK
243 let unsafety = self.parse_unsafety();
244 self.expect_keyword(kw::Extern)?;
245 self.parse_item_foreign_mod(attrs, unsafety)?
246 } else if self.is_static_global() {
247 // STATIC ITEM
248 self.bump(); // `static`
249 let m = self.parse_mutability();
250 let (ident, ty, expr) = self.parse_item_global(Some(m))?;
251 (ident, ItemKind::Static(ty, m, expr))
252 } else if let Const::Yes(const_span) = self.parse_constness() {
253 // CONST ITEM
254 if self.token.is_keyword(kw::Impl) {
255 // recover from `const impl`, suggest `impl const`
256 self.recover_const_impl(const_span, attrs, def())?
257 } else {
258 self.recover_const_mut(const_span);
259 let (ident, ty, expr) = self.parse_item_global(None)?;
260 (ident, ItemKind::Const(def(), ty, expr))
261 }
262 } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() {
263 // TRAIT ITEM
264 self.parse_item_trait(attrs, lo)?
265 } else if self.check_keyword(kw::Impl)
266 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl])
267 {
268 // IMPL ITEM
269 self.parse_item_impl(attrs, def())?
270 } else if self.check_keyword(kw::Mod)
271 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod])
272 {
273 // MODULE ITEM
274 self.parse_item_mod(attrs)?
275 } else if self.eat_keyword(kw::Type) {
276 // TYPE ITEM
277 self.parse_type_alias(def())?
278 } else if self.eat_keyword(kw::Enum) {
279 // ENUM ITEM
280 self.parse_item_enum()?
281 } else if self.eat_keyword(kw::Struct) {
282 // STRUCT ITEM
283 self.parse_item_struct()?
284 } else if self.is_kw_followed_by_ident(kw::Union) {
285 // UNION ITEM
286 self.bump(); // `union`
287 self.parse_item_union()?
288 } else if self.eat_keyword(kw::Macro) {
289 // MACROS 2.0 ITEM
290 self.parse_item_decl_macro(lo)?
291 } else if self.is_macro_rules_item() {
292 // MACRO_RULES ITEM
293 self.parse_item_macro_rules(vis)?
294 } else if vis.kind.is_pub() && self.isnt_macro_invocation() {
295 self.recover_missing_kw_before_item()?;
296 return Ok(None);
297 } else if macros_allowed && self.check_path() {
298 // MACRO INVOCATION ITEM
299 (Ident::invalid(), ItemKind::MacCall(self.parse_item_macro(vis)?))
300 } else {
301 return Ok(None);
302 };
303 Ok(Some(info))
304 }
305
306 /// When parsing a statement, would the start of a path be an item?
307 pub(super) fn is_path_start_item(&mut self) -> bool {
308 self.is_crate_vis() // no: `crate::b`, yes: `crate $item`
309 || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }`
310 || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }`
311 || self.is_async_fn() // no(2015): `async::b`, yes: `async fn`
312 || self.is_macro_rules_item() // no: `macro_rules::b`, yes: `macro_rules! mac`
313 }
314
315 /// Are we sure this could not possibly be a macro invocation?
316 fn isnt_macro_invocation(&mut self) -> bool {
317 self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep)
318 }
319
320 /// Recover on encountering a struct or method definition where the user
321 /// forgot to add the `struct` or `fn` keyword after writing `pub`: `pub S {}`.
322 fn recover_missing_kw_before_item(&mut self) -> PResult<'a, ()> {
323 // Space between `pub` keyword and the identifier
324 //
325 // pub S {}
326 // ^^^ `sp` points here
327 let sp = self.prev_token.span.between(self.token.span);
328 let full_sp = self.prev_token.span.to(self.token.span);
329 let ident_sp = self.token.span;
330 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
331 // possible public struct definition where `struct` was forgotten
332 let ident = self.parse_ident().unwrap();
333 let msg = format!("add `struct` here to parse `{}` as a public struct", ident);
334 let mut err = self.struct_span_err(sp, "missing `struct` for struct definition");
335 err.span_suggestion_short(
336 sp,
337 &msg,
338 " struct ".into(),
339 Applicability::MaybeIncorrect, // speculative
340 );
341 Err(err)
342 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
343 let ident = self.parse_ident().unwrap();
344 self.bump(); // `(`
345 let kw_name = self.recover_first_param();
346 self.consume_block(token::Paren, ConsumeClosingDelim::Yes);
347 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
348 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
349 self.bump(); // `{`
350 ("fn", kw_name, false)
351 } else if self.check(&token::OpenDelim(token::Brace)) {
352 self.bump(); // `{`
353 ("fn", kw_name, false)
354 } else if self.check(&token::Colon) {
355 let kw = "struct";
356 (kw, kw, false)
357 } else {
358 ("fn` or `struct", "function or struct", true)
359 };
360
361 let msg = format!("missing `{}` for {} definition", kw, kw_name);
362 let mut err = self.struct_span_err(sp, &msg);
363 if !ambiguous {
364 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
365 let suggestion =
366 format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name);
367 err.span_suggestion_short(
368 sp,
369 &suggestion,
370 format!(" {} ", kw),
371 Applicability::MachineApplicable,
372 );
373 } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
374 err.span_suggestion(
375 full_sp,
376 "if you meant to call a macro, try",
377 format!("{}!", snippet),
378 // this is the `ambiguous` conditional branch
379 Applicability::MaybeIncorrect,
380 );
381 } else {
382 err.help(
383 "if you meant to call a macro, remove the `pub` \
384 and add a trailing `!` after the identifier",
385 );
386 }
387 Err(err)
388 } else if self.look_ahead(1, |t| *t == token::Lt) {
389 let ident = self.parse_ident().unwrap();
390 self.eat_to_tokens(&[&token::Gt]);
391 self.bump(); // `>`
392 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
393 ("fn", self.recover_first_param(), false)
394 } else if self.check(&token::OpenDelim(token::Brace)) {
395 ("struct", "struct", false)
396 } else {
397 ("fn` or `struct", "function or struct", true)
398 };
399 let msg = format!("missing `{}` for {} definition", kw, kw_name);
400 let mut err = self.struct_span_err(sp, &msg);
401 if !ambiguous {
402 err.span_suggestion_short(
403 sp,
404 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
405 format!(" {} ", kw),
406 Applicability::MachineApplicable,
407 );
408 }
409 Err(err)
410 } else {
411 Ok(())
412 }
413 }
414
415 /// Parses an item macro, e.g., `item!();`.
416 fn parse_item_macro(&mut self, vis: &Visibility) -> PResult<'a, MacCall> {
417 let path = self.parse_path(PathStyle::Mod)?; // `foo::bar`
418 self.expect(&token::Not)?; // `!`
419 let args = self.parse_mac_args()?; // `( .. )` or `[ .. ]` (followed by `;`), or `{ .. }`.
420 self.eat_semi_for_macro_if_needed(&args);
421 self.complain_if_pub_macro(vis, false);
422 Ok(MacCall { path, args, prior_type_ascription: self.last_type_ascription })
423 }
424
425 /// Recover if we parsed attributes and expected an item but there was none.
426 fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
427 let (start, end) = match attrs {
428 [] => return Ok(()),
429 [x0 @ xn] | [x0, .., xn] => (x0, xn),
430 };
431 let msg = if end.is_doc_comment() {
432 "expected item after doc comment"
433 } else {
434 "expected item after attributes"
435 };
436 let mut err = self.struct_span_err(end.span, msg);
437 if end.is_doc_comment() {
438 err.span_label(end.span, "this doc comment doesn't document anything");
439 }
440 if let [.., penultimate, _] = attrs {
441 err.span_label(start.span.to(penultimate.span), "other attributes here");
442 }
443 Err(err)
444 }
445
446 fn is_async_fn(&self) -> bool {
447 self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn])
448 }
449
450 fn parse_polarity(&mut self) -> ast::ImplPolarity {
451 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
452 if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
453 self.bump(); // `!`
454 ast::ImplPolarity::Negative(self.prev_token.span)
455 } else {
456 ast::ImplPolarity::Positive
457 }
458 }
459
460 /// Parses an implementation item.
461 ///
462 /// ```
463 /// impl<'a, T> TYPE { /* impl items */ }
464 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
465 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
466 /// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
467 /// ```
468 ///
469 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
470 /// ```
471 /// "impl" GENERICS "const"? "!"? TYPE "for"? (TYPE | "..") ("where" PREDICATES)? "{" BODY "}"
472 /// "impl" GENERICS "const"? "!"? TYPE ("where" PREDICATES)? "{" BODY "}"
473 /// ```
474 fn parse_item_impl(
475 &mut self,
476 attrs: &mut Vec<Attribute>,
477 defaultness: Defaultness,
478 ) -> PResult<'a, ItemInfo> {
479 let unsafety = self.parse_unsafety();
480 self.expect_keyword(kw::Impl)?;
481
482 // First, parse generic parameters if necessary.
483 let mut generics = if self.choose_generics_over_qpath(0) {
484 self.parse_generics()?
485 } else {
486 let mut generics = Generics::default();
487 // impl A for B {}
488 // /\ this is where `generics.span` should point when there are no type params.
489 generics.span = self.prev_token.span.shrink_to_hi();
490 generics
491 };
492
493 let constness = self.parse_constness();
494 if let Const::Yes(span) = constness {
495 self.sess.gated_spans.gate(sym::const_trait_impl, span);
496 }
497
498 let polarity = self.parse_polarity();
499
500 // Parse both types and traits as a type, then reinterpret if necessary.
501 let err_path = |span| ast::Path::from_ident(Ident::new(kw::Empty, span));
502 let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt)
503 {
504 let span = self.prev_token.span.between(self.token.span);
505 self.struct_span_err(span, "missing trait in a trait impl").emit();
506 P(Ty {
507 kind: TyKind::Path(None, err_path(span)),
508 span,
509 id: DUMMY_NODE_ID,
510 tokens: None,
511 })
512 } else {
513 self.parse_ty()?
514 };
515
516 // If `for` is missing we try to recover.
517 let has_for = self.eat_keyword(kw::For);
518 let missing_for_span = self.prev_token.span.between(self.token.span);
519
520 let ty_second = if self.token == token::DotDot {
521 // We need to report this error after `cfg` expansion for compatibility reasons
522 self.bump(); // `..`, do not add it to expected tokens
523 Some(self.mk_ty(self.prev_token.span, TyKind::Err))
524 } else if has_for || self.token.can_begin_type() {
525 Some(self.parse_ty()?)
526 } else {
527 None
528 };
529
530 generics.where_clause = self.parse_where_clause()?;
531
532 let impl_items = self.parse_item_list(attrs, |p| p.parse_impl_item())?;
533
534 let item_kind = match ty_second {
535 Some(ty_second) => {
536 // impl Trait for Type
537 if !has_for {
538 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
539 .span_suggestion_short(
540 missing_for_span,
541 "add `for` here",
542 " for ".to_string(),
543 Applicability::MachineApplicable,
544 )
545 .emit();
546 }
547
548 let ty_first = ty_first.into_inner();
549 let path = match ty_first.kind {
550 // This notably includes paths passed through `ty` macro fragments (#46438).
551 TyKind::Path(None, path) => path,
552 _ => {
553 self.struct_span_err(ty_first.span, "expected a trait, found type").emit();
554 err_path(ty_first.span)
555 }
556 };
557 let trait_ref = TraitRef { path, ref_id: ty_first.id };
558
559 ItemKind::Impl(box ImplKind {
560 unsafety,
561 polarity,
562 defaultness,
563 constness,
564 generics,
565 of_trait: Some(trait_ref),
566 self_ty: ty_second,
567 items: impl_items,
568 })
569 }
570 None => {
571 // impl Type
572 ItemKind::Impl(box ImplKind {
573 unsafety,
574 polarity,
575 defaultness,
576 constness,
577 generics,
578 of_trait: None,
579 self_ty: ty_first,
580 items: impl_items,
581 })
582 }
583 };
584
585 Ok((Ident::invalid(), item_kind))
586 }
587
588 fn parse_item_list<T>(
589 &mut self,
590 attrs: &mut Vec<Attribute>,
591 mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option<Option<T>>>,
592 ) -> PResult<'a, Vec<T>> {
593 let open_brace_span = self.token.span;
594 self.expect(&token::OpenDelim(token::Brace))?;
595 attrs.append(&mut self.parse_inner_attributes()?);
596
597 let mut items = Vec::new();
598 while !self.eat(&token::CloseDelim(token::Brace)) {
599 if self.recover_doc_comment_before_brace() {
600 continue;
601 }
602 match parse_item(self) {
603 Ok(None) => {
604 // We have to bail or we'll potentially never make progress.
605 let non_item_span = self.token.span;
606 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
607 self.struct_span_err(non_item_span, "non-item in item list")
608 .span_label(open_brace_span, "item list starts here")
609 .span_label(non_item_span, "non-item starts here")
610 .span_label(self.prev_token.span, "item list ends here")
611 .emit();
612 break;
613 }
614 Ok(Some(item)) => items.extend(item),
615 Err(mut err) => {
616 self.consume_block(token::Brace, ConsumeClosingDelim::Yes);
617 err.span_label(open_brace_span, "while parsing this item list starting here")
618 .span_label(self.prev_token.span, "the item list ends here")
619 .emit();
620 break;
621 }
622 }
623 }
624 Ok(items)
625 }
626
627 /// Recover on a doc comment before `}`.
628 fn recover_doc_comment_before_brace(&mut self) -> bool {
629 if let token::DocComment(..) = self.token.kind {
630 if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) {
631 struct_span_err!(
632 self.diagnostic(),
633 self.token.span,
634 E0584,
635 "found a documentation comment that doesn't document anything",
636 )
637 .span_label(self.token.span, "this doc comment doesn't document anything")
638 .help(
639 "doc comments must come before what they document, maybe a \
640 comment was intended with `//`?",
641 )
642 .emit();
643 self.bump();
644 return true;
645 }
646 }
647 false
648 }
649
650 /// Parses defaultness (i.e., `default` or nothing).
651 fn parse_defaultness(&mut self) -> Defaultness {
652 // We are interested in `default` followed by another identifier.
653 // However, we must avoid keywords that occur as binary operators.
654 // Currently, the only applicable keyword is `as` (`default as Ty`).
655 if self.check_keyword(kw::Default)
656 && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As))
657 {
658 self.bump(); // `default`
659 Defaultness::Default(self.prev_token.uninterpolated_span())
660 } else {
661 Defaultness::Final
662 }
663 }
664
665 /// Is this an `(unsafe auto? | auto) trait` item?
666 fn check_auto_or_unsafe_trait_item(&mut self) -> bool {
667 // auto trait
668 self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])
669 // unsafe auto trait
670 || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
671 }
672
673 /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
674 fn parse_item_trait(&mut self, attrs: &mut Vec<Attribute>, lo: Span) -> PResult<'a, ItemInfo> {
675 let unsafety = self.parse_unsafety();
676 // Parse optional `auto` prefix.
677 let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No };
678
679 self.expect_keyword(kw::Trait)?;
680 let ident = self.parse_ident()?;
681 let mut tps = self.parse_generics()?;
682
683 // Parse optional colon and supertrait bounds.
684 let had_colon = self.eat(&token::Colon);
685 let span_at_colon = self.prev_token.span;
686 let bounds = if had_colon {
687 self.parse_generic_bounds(Some(self.prev_token.span))?
688 } else {
689 Vec::new()
690 };
691
692 let span_before_eq = self.prev_token.span;
693 if self.eat(&token::Eq) {
694 // It's a trait alias.
695 if had_colon {
696 let span = span_at_colon.to(span_before_eq);
697 self.struct_span_err(span, "bounds are not allowed on trait aliases").emit();
698 }
699
700 let bounds = self.parse_generic_bounds(None)?;
701 tps.where_clause = self.parse_where_clause()?;
702 self.expect_semi()?;
703
704 let whole_span = lo.to(self.prev_token.span);
705 if is_auto == IsAuto::Yes {
706 let msg = "trait aliases cannot be `auto`";
707 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
708 }
709 if let Unsafe::Yes(_) = unsafety {
710 let msg = "trait aliases cannot be `unsafe`";
711 self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit();
712 }
713
714 self.sess.gated_spans.gate(sym::trait_alias, whole_span);
715
716 Ok((ident, ItemKind::TraitAlias(tps, bounds)))
717 } else {
718 // It's a normal trait.
719 tps.where_clause = self.parse_where_clause()?;
720 let items = self.parse_item_list(attrs, |p| p.parse_trait_item())?;
721 Ok((ident, ItemKind::Trait(box TraitKind(is_auto, unsafety, tps, bounds, items))))
722 }
723 }
724
725 pub fn parse_impl_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
726 self.parse_assoc_item(|_| true)
727 }
728
729 pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
730 self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
731 }
732
733 /// Parses associated items.
734 fn parse_assoc_item(&mut self, req_name: ReqName) -> PResult<'a, Option<Option<P<AssocItem>>>> {
735 Ok(self.parse_item_(req_name, ForceCollect::No)?.map(
736 |Item { attrs, id, span, vis, ident, kind, tokens }| {
737 let kind = match AssocItemKind::try_from(kind) {
738 Ok(kind) => kind,
739 Err(kind) => match kind {
740 ItemKind::Static(a, _, b) => {
741 self.struct_span_err(span, "associated `static` items are not allowed")
742 .emit();
743 AssocItemKind::Const(Defaultness::Final, a, b)
744 }
745 _ => return self.error_bad_item_kind(span, &kind, "`trait`s or `impl`s"),
746 },
747 };
748 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
749 },
750 ))
751 }
752
753 /// Parses a `type` alias with the following grammar:
754 /// ```
755 /// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
756 /// ```
757 /// The `"type"` has already been eaten.
758 fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
759 let ident = self.parse_ident()?;
760 let mut generics = self.parse_generics()?;
761
762 // Parse optional colon and param bounds.
763 let bounds =
764 if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
765 generics.where_clause = self.parse_where_clause()?;
766
767 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
768 self.expect_semi()?;
769
770 Ok((ident, ItemKind::TyAlias(box TyAliasKind(def, generics, bounds, default))))
771 }
772
773 /// Parses a `UseTree`.
774 ///
775 /// ```text
776 /// USE_TREE = [`::`] `*` |
777 /// [`::`] `{` USE_TREE_LIST `}` |
778 /// PATH `::` `*` |
779 /// PATH `::` `{` USE_TREE_LIST `}` |
780 /// PATH [`as` IDENT]
781 /// ```
782 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
783 let lo = self.token.span;
784
785 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None };
786 let kind = if self.check(&token::OpenDelim(token::Brace))
787 || self.check(&token::BinOp(token::Star))
788 || self.is_import_coupler()
789 {
790 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
791 let mod_sep_ctxt = self.token.span.ctxt();
792 if self.eat(&token::ModSep) {
793 prefix
794 .segments
795 .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
796 }
797
798 self.parse_use_tree_glob_or_nested()?
799 } else {
800 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
801 prefix = self.parse_path(PathStyle::Mod)?;
802
803 if self.eat(&token::ModSep) {
804 self.parse_use_tree_glob_or_nested()?
805 } else {
806 UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID)
807 }
808 };
809
810 Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) })
811 }
812
813 /// Parses `*` or `{...}`.
814 fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> {
815 Ok(if self.eat(&token::BinOp(token::Star)) {
816 UseTreeKind::Glob
817 } else {
818 UseTreeKind::Nested(self.parse_use_tree_list()?)
819 })
820 }
821
822 /// Parses a `UseTreeKind::Nested(list)`.
823 ///
824 /// ```text
825 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
826 /// ```
827 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
828 self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID)))
829 .map(|(r, _)| r)
830 }
831
832 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
833 if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) }
834 }
835
836 fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> {
837 match self.token.ident() {
838 Some((ident @ Ident { name: kw::Underscore, .. }, false)) => {
839 self.bump();
840 Ok(ident)
841 }
842 _ => self.parse_ident(),
843 }
844 }
845
846 /// Parses `extern crate` links.
847 ///
848 /// # Examples
849 ///
850 /// ```
851 /// extern crate foo;
852 /// extern crate bar as foo;
853 /// ```
854 fn parse_item_extern_crate(&mut self) -> PResult<'a, ItemInfo> {
855 // Accept `extern crate name-like-this` for better diagnostics
856 let orig_name = self.parse_crate_name_with_dashes()?;
857 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
858 (rename, Some(orig_name.name))
859 } else {
860 (orig_name, None)
861 };
862 self.expect_semi()?;
863 Ok((item_name, ItemKind::ExternCrate(orig_name)))
864 }
865
866 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, Ident> {
867 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
868 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
869 in the code";
870 let mut ident = if self.token.is_keyword(kw::SelfLower) {
871 self.parse_path_segment_ident()
872 } else {
873 self.parse_ident()
874 }?;
875 let mut idents = vec![];
876 let mut replacement = vec![];
877 let mut fixed_crate_name = false;
878 // Accept `extern crate name-like-this` for better diagnostics.
879 let dash = token::BinOp(token::BinOpToken::Minus);
880 if self.token == dash {
881 // Do not include `-` as part of the expected tokens list.
882 while self.eat(&dash) {
883 fixed_crate_name = true;
884 replacement.push((self.prev_token.span, "_".to_string()));
885 idents.push(self.parse_ident()?);
886 }
887 }
888 if fixed_crate_name {
889 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
890 let mut fixed_name = format!("{}", ident.name);
891 for part in idents {
892 fixed_name.push_str(&format!("_{}", part.name));
893 }
894 ident = Ident::from_str_and_span(&fixed_name, fixed_name_sp);
895
896 self.struct_span_err(fixed_name_sp, error_msg)
897 .span_label(fixed_name_sp, "dash-separated idents are not valid")
898 .multipart_suggestion(suggestion_msg, replacement, Applicability::MachineApplicable)
899 .emit();
900 }
901 Ok(ident)
902 }
903
904 /// Parses `extern` for foreign ABIs modules.
905 ///
906 /// `extern` is expected to have been consumed before calling this method.
907 ///
908 /// # Examples
909 ///
910 /// ```ignore (only-for-syntax-highlight)
911 /// extern "C" {}
912 /// extern {}
913 /// ```
914 fn parse_item_foreign_mod(
915 &mut self,
916 attrs: &mut Vec<Attribute>,
917 unsafety: Unsafe,
918 ) -> PResult<'a, ItemInfo> {
919 let abi = self.parse_abi(); // ABI?
920 let items = self.parse_item_list(attrs, |p| p.parse_foreign_item())?;
921 let module = ast::ForeignMod { unsafety, abi, items };
922 Ok((Ident::invalid(), ItemKind::ForeignMod(module)))
923 }
924
925 /// Parses a foreign item (one in an `extern { ... }` block).
926 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<Option<P<ForeignItem>>>> {
927 Ok(self.parse_item_(|_| true, ForceCollect::No)?.map(
928 |Item { attrs, id, span, vis, ident, kind, tokens }| {
929 let kind = match ForeignItemKind::try_from(kind) {
930 Ok(kind) => kind,
931 Err(kind) => match kind {
932 ItemKind::Const(_, a, b) => {
933 self.error_on_foreign_const(span, ident);
934 ForeignItemKind::Static(a, Mutability::Not, b)
935 }
936 _ => return self.error_bad_item_kind(span, &kind, "`extern` blocks"),
937 },
938 };
939 Some(P(Item { attrs, id, span, vis, ident, kind, tokens }))
940 },
941 ))
942 }
943
944 fn error_bad_item_kind<T>(&self, span: Span, kind: &ItemKind, ctx: &str) -> Option<T> {
945 let span = self.sess.source_map().guess_head_span(span);
946 let descr = kind.descr();
947 self.struct_span_err(span, &format!("{} is not supported in {}", descr, ctx))
948 .help(&format!("consider moving the {} out to a nearby module scope", descr))
949 .emit();
950 None
951 }
952
953 fn error_on_foreign_const(&self, span: Span, ident: Ident) {
954 self.struct_span_err(ident.span, "extern items cannot be `const`")
955 .span_suggestion(
956 span.with_hi(ident.span.lo()),
957 "try using a static value",
958 "static ".to_string(),
959 Applicability::MachineApplicable,
960 )
961 .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html")
962 .emit();
963 }
964
965 fn is_unsafe_foreign_mod(&self) -> bool {
966 self.token.is_keyword(kw::Unsafe)
967 && self.is_keyword_ahead(1, &[kw::Extern])
968 && self.look_ahead(
969 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize),
970 |t| t.kind == token::OpenDelim(token::Brace),
971 )
972 }
973
974 fn is_static_global(&mut self) -> bool {
975 if self.check_keyword(kw::Static) {
976 // Check if this could be a closure.
977 !self.look_ahead(1, |token| {
978 if token.is_keyword(kw::Move) {
979 return true;
980 }
981 matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
982 })
983 } else {
984 false
985 }
986 }
987
988 /// Recover on `const mut` with `const` already eaten.
989 fn recover_const_mut(&mut self, const_span: Span) {
990 if self.eat_keyword(kw::Mut) {
991 let span = self.prev_token.span;
992 self.struct_span_err(span, "const globals cannot be mutable")
993 .span_label(span, "cannot be mutable")
994 .span_suggestion(
995 const_span,
996 "you might want to declare a static instead",
997 "static".to_owned(),
998 Applicability::MaybeIncorrect,
999 )
1000 .emit();
1001 }
1002 }
1003
1004 /// Recover on `const impl` with `const` already eaten.
1005 fn recover_const_impl(
1006 &mut self,
1007 const_span: Span,
1008 attrs: &mut Vec<Attribute>,
1009 defaultness: Defaultness,
1010 ) -> PResult<'a, ItemInfo> {
1011 let impl_span = self.token.span;
1012 let mut err = self.expected_ident_found();
1013
1014 // Only try to recover if this is implementing a trait for a type
1015 let mut impl_info = match self.parse_item_impl(attrs, defaultness) {
1016 Ok(impl_info) => impl_info,
1017 Err(mut recovery_error) => {
1018 // Recovery failed, raise the "expected identifier" error
1019 recovery_error.cancel();
1020 return Err(err);
1021 }
1022 };
1023
1024 match impl_info.1 {
1025 ItemKind::Impl(box ImplKind {
1026 of_trait: Some(ref trai), ref mut constness, ..
1027 }) => {
1028 *constness = Const::Yes(const_span);
1029
1030 let before_trait = trai.path.span.shrink_to_lo();
1031 let const_up_to_impl = const_span.with_hi(impl_span.lo());
1032 err.multipart_suggestion(
1033 "you might have meant to write a const trait impl",
1034 vec![(const_up_to_impl, "".to_owned()), (before_trait, "const ".to_owned())],
1035 Applicability::MaybeIncorrect,
1036 )
1037 .emit();
1038 }
1039 ItemKind::Impl { .. } => return Err(err),
1040 _ => unreachable!(),
1041 }
1042
1043 Ok(impl_info)
1044 }
1045
1046 /// Parse `["const" | ("static" "mut"?)] $ident ":" $ty (= $expr)?` with
1047 /// `["const" | ("static" "mut"?)]` already parsed and stored in `m`.
1048 ///
1049 /// When `m` is `"const"`, `$ident` may also be `"_"`.
1050 fn parse_item_global(
1051 &mut self,
1052 m: Option<Mutability>,
1053 ) -> PResult<'a, (Ident, P<Ty>, Option<P<ast::Expr>>)> {
1054 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
1055
1056 // Parse the type of a `const` or `static mut?` item.
1057 // That is, the `":" $ty` fragment.
1058 let ty = if self.eat(&token::Colon) {
1059 self.parse_ty()?
1060 } else {
1061 self.recover_missing_const_type(id, m)
1062 };
1063
1064 let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None };
1065 self.expect_semi()?;
1066 Ok((id, ty, expr))
1067 }
1068
1069 /// We were supposed to parse `:` but the `:` was missing.
1070 /// This means that the type is missing.
1071 fn recover_missing_const_type(&mut self, id: Ident, m: Option<Mutability>) -> P<Ty> {
1072 // Construct the error and stash it away with the hope
1073 // that typeck will later enrich the error with a type.
1074 let kind = match m {
1075 Some(Mutability::Mut) => "static mut",
1076 Some(Mutability::Not) => "static",
1077 None => "const",
1078 };
1079 let mut err = self.struct_span_err(id.span, &format!("missing type for `{}` item", kind));
1080 err.span_suggestion(
1081 id.span,
1082 "provide a type for the item",
1083 format!("{}: <type>", id),
1084 Applicability::HasPlaceholders,
1085 );
1086 err.stash(id.span, StashKey::ItemNoType);
1087
1088 // The user intended that the type be inferred,
1089 // so treat this as if the user wrote e.g. `const A: _ = expr;`.
1090 P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID, tokens: None })
1091 }
1092
1093 /// Parses an enum declaration.
1094 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
1095 let id = self.parse_ident()?;
1096 let mut generics = self.parse_generics()?;
1097 generics.where_clause = self.parse_where_clause()?;
1098
1099 let (variants, _) =
1100 self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| {
1101 self.recover_stmt();
1102 e
1103 })?;
1104
1105 let enum_definition =
1106 EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() };
1107 Ok((id, ItemKind::Enum(enum_definition, generics)))
1108 }
1109
1110 fn parse_enum_variant(&mut self) -> PResult<'a, Option<Variant>> {
1111 let variant_attrs = self.parse_outer_attributes()?;
1112 let vlo = self.token.span;
1113
1114 let vis = self.parse_visibility(FollowedByType::No)?;
1115 if !self.recover_nested_adt_item(kw::Enum)? {
1116 return Ok(None);
1117 }
1118 let ident = self.parse_ident()?;
1119
1120 let struct_def = if self.check(&token::OpenDelim(token::Brace)) {
1121 // Parse a struct variant.
1122 let (fields, recovered) = self.parse_record_struct_body()?;
1123 VariantData::Struct(fields, recovered)
1124 } else if self.check(&token::OpenDelim(token::Paren)) {
1125 VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID)
1126 } else {
1127 VariantData::Unit(DUMMY_NODE_ID)
1128 };
1129
1130 let disr_expr =
1131 if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None };
1132
1133 let vr = ast::Variant {
1134 ident,
1135 vis,
1136 id: DUMMY_NODE_ID,
1137 attrs: variant_attrs,
1138 data: struct_def,
1139 disr_expr,
1140 span: vlo.to(self.prev_token.span),
1141 is_placeholder: false,
1142 };
1143
1144 Ok(Some(vr))
1145 }
1146
1147 /// Parses `struct Foo { ... }`.
1148 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
1149 let class_name = self.parse_ident()?;
1150
1151 let mut generics = self.parse_generics()?;
1152
1153 // There is a special case worth noting here, as reported in issue #17904.
1154 // If we are parsing a tuple struct it is the case that the where clause
1155 // should follow the field list. Like so:
1156 //
1157 // struct Foo<T>(T) where T: Copy;
1158 //
1159 // If we are parsing a normal record-style struct it is the case
1160 // that the where clause comes before the body, and after the generics.
1161 // So if we look ahead and see a brace or a where-clause we begin
1162 // parsing a record style struct.
1163 //
1164 // Otherwise if we look ahead and see a paren we parse a tuple-style
1165 // struct.
1166
1167 let vdata = if self.token.is_keyword(kw::Where) {
1168 generics.where_clause = self.parse_where_clause()?;
1169 if self.eat(&token::Semi) {
1170 // If we see a: `struct Foo<T> where T: Copy;` style decl.
1171 VariantData::Unit(DUMMY_NODE_ID)
1172 } else {
1173 // If we see: `struct Foo<T> where T: Copy { ... }`
1174 let (fields, recovered) = self.parse_record_struct_body()?;
1175 VariantData::Struct(fields, recovered)
1176 }
1177 // No `where` so: `struct Foo<T>;`
1178 } else if self.eat(&token::Semi) {
1179 VariantData::Unit(DUMMY_NODE_ID)
1180 // Record-style struct definition
1181 } else if self.token == token::OpenDelim(token::Brace) {
1182 let (fields, recovered) = self.parse_record_struct_body()?;
1183 VariantData::Struct(fields, recovered)
1184 // Tuple-style struct definition with optional where-clause.
1185 } else if self.token == token::OpenDelim(token::Paren) {
1186 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID);
1187 generics.where_clause = self.parse_where_clause()?;
1188 self.expect_semi()?;
1189 body
1190 } else {
1191 let token_str = super::token_descr(&self.token);
1192 let msg = &format!(
1193 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
1194 token_str
1195 );
1196 let mut err = self.struct_span_err(self.token.span, msg);
1197 err.span_label(self.token.span, "expected `where`, `{`, `(`, or `;` after struct name");
1198 return Err(err);
1199 };
1200
1201 Ok((class_name, ItemKind::Struct(vdata, generics)))
1202 }
1203
1204 /// Parses `union Foo { ... }`.
1205 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
1206 let class_name = self.parse_ident()?;
1207
1208 let mut generics = self.parse_generics()?;
1209
1210 let vdata = if self.token.is_keyword(kw::Where) {
1211 generics.where_clause = self.parse_where_clause()?;
1212 let (fields, recovered) = self.parse_record_struct_body()?;
1213 VariantData::Struct(fields, recovered)
1214 } else if self.token == token::OpenDelim(token::Brace) {
1215 let (fields, recovered) = self.parse_record_struct_body()?;
1216 VariantData::Struct(fields, recovered)
1217 } else {
1218 let token_str = super::token_descr(&self.token);
1219 let msg = &format!("expected `where` or `{{` after union name, found {}", token_str);
1220 let mut err = self.struct_span_err(self.token.span, msg);
1221 err.span_label(self.token.span, "expected `where` or `{` after union name");
1222 return Err(err);
1223 };
1224
1225 Ok((class_name, ItemKind::Union(vdata, generics)))
1226 }
1227
1228 fn parse_record_struct_body(
1229 &mut self,
1230 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
1231 let mut fields = Vec::new();
1232 let mut recovered = false;
1233 if self.eat(&token::OpenDelim(token::Brace)) {
1234 while self.token != token::CloseDelim(token::Brace) {
1235 let field = self.parse_struct_decl_field().map_err(|e| {
1236 self.consume_block(token::Brace, ConsumeClosingDelim::No);
1237 recovered = true;
1238 e
1239 });
1240 match field {
1241 Ok(field) => fields.push(field),
1242 Err(mut err) => {
1243 err.emit();
1244 break;
1245 }
1246 }
1247 }
1248 self.eat(&token::CloseDelim(token::Brace));
1249 } else {
1250 let token_str = super::token_descr(&self.token);
1251 let msg = &format!("expected `where`, or `{{` after struct name, found {}", token_str);
1252 let mut err = self.struct_span_err(self.token.span, msg);
1253 err.span_label(self.token.span, "expected `where`, or `{` after struct name");
1254 return Err(err);
1255 }
1256
1257 Ok((fields, recovered))
1258 }
1259
1260 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
1261 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
1262 // Unit like structs are handled in parse_item_struct function
1263 self.parse_paren_comma_seq(|p| {
1264 let attrs = p.parse_outer_attributes()?;
1265 let lo = p.token.span;
1266 let vis = p.parse_visibility(FollowedByType::Yes)?;
1267 let ty = p.parse_ty()?;
1268 Ok(StructField {
1269 span: lo.to(ty.span),
1270 vis,
1271 ident: None,
1272 id: DUMMY_NODE_ID,
1273 ty,
1274 attrs,
1275 is_placeholder: false,
1276 })
1277 })
1278 .map(|(r, _)| r)
1279 }
1280
1281 /// Parses an element of a struct declaration.
1282 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
1283 let attrs = self.parse_outer_attributes()?;
1284 let lo = self.token.span;
1285 let vis = self.parse_visibility(FollowedByType::No)?;
1286 self.parse_single_struct_field(lo, vis, attrs)
1287 }
1288
1289 /// Parses a structure field declaration.
1290 fn parse_single_struct_field(
1291 &mut self,
1292 lo: Span,
1293 vis: Visibility,
1294 attrs: Vec<Attribute>,
1295 ) -> PResult<'a, StructField> {
1296 let mut seen_comma: bool = false;
1297 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
1298 if self.token == token::Comma {
1299 seen_comma = true;
1300 }
1301 match self.token.kind {
1302 token::Comma => {
1303 self.bump();
1304 }
1305 token::CloseDelim(token::Brace) => {}
1306 token::DocComment(..) => {
1307 let previous_span = self.prev_token.span;
1308 let mut err = self.span_fatal_err(self.token.span, Error::UselessDocComment);
1309 self.bump(); // consume the doc comment
1310 let comma_after_doc_seen = self.eat(&token::Comma);
1311 // `seen_comma` is always false, because we are inside doc block
1312 // condition is here to make code more readable
1313 if !seen_comma && comma_after_doc_seen {
1314 seen_comma = true;
1315 }
1316 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
1317 err.emit();
1318 } else {
1319 if !seen_comma {
1320 let sp = self.sess.source_map().next_point(previous_span);
1321 err.span_suggestion(
1322 sp,
1323 "missing comma here",
1324 ",".into(),
1325 Applicability::MachineApplicable,
1326 );
1327 }
1328 return Err(err);
1329 }
1330 }
1331 _ => {
1332 let sp = self.prev_token.span.shrink_to_hi();
1333 let mut err = self.struct_span_err(
1334 sp,
1335 &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)),
1336 );
1337
1338 // Try to recover extra trailing angle brackets
1339 let mut recovered = false;
1340 if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind {
1341 if let Some(last_segment) = segments.last() {
1342 recovered = self.check_trailing_angle_brackets(
1343 last_segment,
1344 &[&token::Comma, &token::CloseDelim(token::Brace)],
1345 );
1346 if recovered {
1347 // Handle a case like `Vec<u8>>,` where we can continue parsing fields
1348 // after the comma
1349 self.eat(&token::Comma);
1350 // `check_trailing_angle_brackets` already emitted a nicer error
1351 err.cancel();
1352 }
1353 }
1354 }
1355
1356 if self.token.is_ident() {
1357 // This is likely another field; emit the diagnostic and keep going
1358 err.span_suggestion(
1359 sp,
1360 "try adding a comma",
1361 ",".into(),
1362 Applicability::MachineApplicable,
1363 );
1364 err.emit();
1365 recovered = true;
1366 }
1367
1368 if recovered {
1369 // Make sure an error was emitted (either by recovering an angle bracket,
1370 // or by finding an identifier as the next token), since we're
1371 // going to continue parsing
1372 assert!(self.sess.span_diagnostic.has_errors());
1373 } else {
1374 return Err(err);
1375 }
1376 }
1377 }
1378 Ok(a_var)
1379 }
1380
1381 /// Parses a structure field.
1382 fn parse_name_and_ty(
1383 &mut self,
1384 lo: Span,
1385 vis: Visibility,
1386 attrs: Vec<Attribute>,
1387 ) -> PResult<'a, StructField> {
1388 let name = self.parse_ident_common(false)?;
1389 self.expect(&token::Colon)?;
1390 let ty = self.parse_ty()?;
1391 Ok(StructField {
1392 span: lo.to(self.prev_token.span),
1393 ident: Some(name),
1394 vis,
1395 id: DUMMY_NODE_ID,
1396 ty,
1397 attrs,
1398 is_placeholder: false,
1399 })
1400 }
1401
1402 /// Parses a declarative macro 2.0 definition.
1403 /// The `macro` keyword has already been parsed.
1404 /// ```
1405 /// MacBody = "{" TOKEN_STREAM "}" ;
1406 /// MacParams = "(" TOKEN_STREAM ")" ;
1407 /// DeclMac = "macro" Ident MacParams? MacBody ;
1408 /// ```
1409 fn parse_item_decl_macro(&mut self, lo: Span) -> PResult<'a, ItemInfo> {
1410 let ident = self.parse_ident()?;
1411 let body = if self.check(&token::OpenDelim(token::Brace)) {
1412 self.parse_mac_args()? // `MacBody`
1413 } else if self.check(&token::OpenDelim(token::Paren)) {
1414 let params = self.parse_token_tree(); // `MacParams`
1415 let pspan = params.span();
1416 if !self.check(&token::OpenDelim(token::Brace)) {
1417 return self.unexpected();
1418 }
1419 let body = self.parse_token_tree(); // `MacBody`
1420 // Convert `MacParams MacBody` into `{ MacParams => MacBody }`.
1421 let bspan = body.span();
1422 let arrow = TokenTree::token(token::FatArrow, pspan.between(bspan)); // `=>`
1423 let tokens = TokenStream::new(vec![params.into(), arrow.into(), body.into()]);
1424 let dspan = DelimSpan::from_pair(pspan.shrink_to_lo(), bspan.shrink_to_hi());
1425 P(MacArgs::Delimited(dspan, MacDelimiter::Brace, tokens))
1426 } else {
1427 return self.unexpected();
1428 };
1429
1430 self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
1431 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
1432 }
1433
1434 /// Is this unambiguously the start of a `macro_rules! foo` item defnition?
1435 fn is_macro_rules_item(&mut self) -> bool {
1436 self.check_keyword(kw::MacroRules)
1437 && self.look_ahead(1, |t| *t == token::Not)
1438 && self.look_ahead(2, |t| t.is_ident())
1439 }
1440
1441 /// Parses a `macro_rules! foo { ... }` declarative macro.
1442 fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
1443 self.expect_keyword(kw::MacroRules)?; // `macro_rules`
1444 self.expect(&token::Not)?; // `!`
1445
1446 let ident = self.parse_ident()?;
1447 let body = self.parse_mac_args()?;
1448 self.eat_semi_for_macro_if_needed(&body);
1449 self.complain_if_pub_macro(vis, true);
1450
1451 Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
1452 }
1453
1454 /// Item macro invocations or `macro_rules!` definitions need inherited visibility.
1455 /// If that's not the case, emit an error.
1456 fn complain_if_pub_macro(&self, vis: &Visibility, macro_rules: bool) {
1457 if let VisibilityKind::Inherited = vis.kind {
1458 return;
1459 }
1460
1461 let vstr = pprust::vis_to_string(vis);
1462 let vstr = vstr.trim_end();
1463 if macro_rules {
1464 let msg = format!("can't qualify macro_rules invocation with `{}`", vstr);
1465 self.struct_span_err(vis.span, &msg)
1466 .span_suggestion(
1467 vis.span,
1468 "try exporting the macro",
1469 "#[macro_export]".to_owned(),
1470 Applicability::MaybeIncorrect, // speculative
1471 )
1472 .emit();
1473 } else {
1474 self.struct_span_err(vis.span, "can't qualify macro invocation with `pub`")
1475 .span_suggestion(
1476 vis.span,
1477 "remove the visibility",
1478 String::new(),
1479 Applicability::MachineApplicable,
1480 )
1481 .help(&format!("try adjusting the macro to put `{}` inside the invocation", vstr))
1482 .emit();
1483 }
1484 }
1485
1486 fn eat_semi_for_macro_if_needed(&mut self, args: &MacArgs) {
1487 if args.need_semicolon() && !self.eat(&token::Semi) {
1488 self.report_invalid_macro_expansion_item(args);
1489 }
1490 }
1491
1492 fn report_invalid_macro_expansion_item(&self, args: &MacArgs) {
1493 let span = args.span().expect("undelimited macro call");
1494 let mut err = self.struct_span_err(
1495 span,
1496 "macros that expand to items must be delimited with braces or followed by a semicolon",
1497 );
1498 if self.unclosed_delims.is_empty() {
1499 let DelimSpan { open, close } = match args {
1500 MacArgs::Empty | MacArgs::Eq(..) => unreachable!(),
1501 MacArgs::Delimited(dspan, ..) => *dspan,
1502 };
1503 err.multipart_suggestion(
1504 "change the delimiters to curly braces",
1505 vec![(open, "{".to_string()), (close, '}'.to_string())],
1506 Applicability::MaybeIncorrect,
1507 );
1508 } else {
1509 err.span_suggestion(
1510 span,
1511 "change the delimiters to curly braces",
1512 " { /* items */ }".to_string(),
1513 Applicability::HasPlaceholders,
1514 );
1515 }
1516 err.span_suggestion(
1517 span.shrink_to_hi(),
1518 "add a semicolon",
1519 ';'.to_string(),
1520 Applicability::MaybeIncorrect,
1521 );
1522 err.emit();
1523 }
1524
1525 /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case
1526 /// it is, we try to parse the item and report error about nested types.
1527 fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> {
1528 if (self.token.is_keyword(kw::Enum)
1529 || self.token.is_keyword(kw::Struct)
1530 || self.token.is_keyword(kw::Union))
1531 && self.look_ahead(1, |t| t.is_ident())
1532 {
1533 let kw_token = self.token.clone();
1534 let kw_str = pprust::token_to_string(&kw_token);
1535 let item = self.parse_item(ForceCollect::No)?;
1536
1537 self.struct_span_err(
1538 kw_token.span,
1539 &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword),
1540 )
1541 .span_suggestion(
1542 item.unwrap().span,
1543 &format!("consider creating a new `{}` definition instead of nesting", kw_str),
1544 String::new(),
1545 Applicability::MaybeIncorrect,
1546 )
1547 .emit();
1548 // We successfully parsed the item but we must inform the caller about nested problem.
1549 return Ok(false);
1550 }
1551 Ok(true)
1552 }
1553 }
1554
1555 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
1556 ///
1557 /// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1558 type ReqName = fn(Edition) -> bool;
1559
1560 /// Parsing of functions and methods.
1561 impl<'a> Parser<'a> {
1562 /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`.
1563 fn parse_fn(
1564 &mut self,
1565 attrs: &mut Vec<Attribute>,
1566 req_name: ReqName,
1567 sig_lo: Span,
1568 ) -> PResult<'a, (Ident, FnSig, Generics, Option<P<Block>>)> {
1569 let header = self.parse_fn_front_matter()?; // `const ... fn`
1570 let ident = self.parse_ident()?; // `foo`
1571 let mut generics = self.parse_generics()?; // `<'a, T, ...>`
1572 let decl = self.parse_fn_decl(req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)`
1573 generics.where_clause = self.parse_where_clause()?; // `where T: Ord`
1574
1575 let mut sig_hi = self.prev_token.span;
1576 let body = self.parse_fn_body(attrs, &ident, &mut sig_hi)?; // `;` or `{ ... }`.
1577 let fn_sig_span = sig_lo.to(sig_hi);
1578 Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body))
1579 }
1580
1581 /// Parse the "body" of a function.
1582 /// This can either be `;` when there's no body,
1583 /// or e.g. a block when the function is a provided one.
1584 fn parse_fn_body(
1585 &mut self,
1586 attrs: &mut Vec<Attribute>,
1587 ident: &Ident,
1588 sig_hi: &mut Span,
1589 ) -> PResult<'a, Option<P<Block>>> {
1590 let (inner_attrs, body) = if self.eat(&token::Semi) {
1591 // Include the trailing semicolon in the span of the signature
1592 *sig_hi = self.prev_token.span;
1593 (Vec::new(), None)
1594 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1595 self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))?
1596 } else if self.token.kind == token::Eq {
1597 // Recover `fn foo() = $expr;`.
1598 self.bump(); // `=`
1599 let eq_sp = self.prev_token.span;
1600 let _ = self.parse_expr()?;
1601 self.expect_semi()?; // `;`
1602 let span = eq_sp.to(self.prev_token.span);
1603 self.struct_span_err(span, "function body cannot be `= expression;`")
1604 .multipart_suggestion(
1605 "surround the expression with `{` and `}` instead of `=` and `;`",
1606 vec![(eq_sp, "{".to_string()), (self.prev_token.span, " }".to_string())],
1607 Applicability::MachineApplicable,
1608 )
1609 .emit();
1610 (Vec::new(), Some(self.mk_block_err(span)))
1611 } else {
1612 if let Err(mut err) =
1613 self.expected_one_of_not_found(&[], &[token::Semi, token::OpenDelim(token::Brace)])
1614 {
1615 if self.token.kind == token::CloseDelim(token::Brace) {
1616 // The enclosing `mod`, `trait` or `impl` is being closed, so keep the `fn` in
1617 // the AST for typechecking.
1618 err.span_label(ident.span, "while parsing this `fn`");
1619 err.emit();
1620 (Vec::new(), None)
1621 } else {
1622 return Err(err);
1623 }
1624 } else {
1625 unreachable!()
1626 }
1627 };
1628 attrs.extend(inner_attrs);
1629 Ok(body)
1630 }
1631
1632 /// Is the current token the start of an `FnHeader` / not a valid parse?
1633 pub(super) fn check_fn_front_matter(&mut self) -> bool {
1634 // We use an over-approximation here.
1635 // `const const`, `fn const` won't parse, but we're not stepping over other syntax either.
1636 const QUALS: [Symbol; 4] = [kw::Const, kw::Async, kw::Unsafe, kw::Extern];
1637 self.check_keyword(kw::Fn) // Definitely an `fn`.
1638 // `$qual fn` or `$qual $qual`:
1639 || QUALS.iter().any(|&kw| self.check_keyword(kw))
1640 && self.look_ahead(1, |t| {
1641 // `$qual fn`, e.g. `const fn` or `async fn`.
1642 t.is_keyword(kw::Fn)
1643 // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`.
1644 || t.is_non_raw_ident_where(|i| QUALS.contains(&i.name)
1645 // Rule out 2015 `const async: T = val`.
1646 && i.is_reserved()
1647 // Rule out unsafe extern block.
1648 && !self.is_unsafe_foreign_mod())
1649 })
1650 // `extern ABI fn`
1651 || self.check_keyword(kw::Extern)
1652 && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus())
1653 && self.look_ahead(2, |t| t.is_keyword(kw::Fn))
1654 }
1655
1656 /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration,
1657 /// up to and including the `fn` keyword. The formal grammar is:
1658 ///
1659 /// ```
1660 /// Extern = "extern" StringLit? ;
1661 /// FnQual = "const"? "async"? "unsafe"? Extern? ;
1662 /// FnFrontMatter = FnQual "fn" ;
1663 /// ```
1664 pub(super) fn parse_fn_front_matter(&mut self) -> PResult<'a, FnHeader> {
1665 let constness = self.parse_constness();
1666 let asyncness = self.parse_asyncness();
1667 let unsafety = self.parse_unsafety();
1668 let ext = self.parse_extern()?;
1669
1670 if let Async::Yes { span, .. } = asyncness {
1671 self.ban_async_in_2015(span);
1672 }
1673
1674 if !self.eat_keyword(kw::Fn) {
1675 // It is possible for `expect_one_of` to recover given the contents of
1676 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
1677 // account for this.
1678 if !self.expect_one_of(&[], &[])? {
1679 unreachable!()
1680 }
1681 }
1682
1683 Ok(FnHeader { constness, unsafety, asyncness, ext })
1684 }
1685
1686 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1687 fn ban_async_in_2015(&self, span: Span) {
1688 if span.rust_2015() {
1689 let diag = self.diagnostic();
1690 struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015")
1691 .span_label(span, "to use `async fn`, switch to Rust 2018 or later")
1692 .help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION))
1693 .note("for more on editions, read https://doc.rust-lang.org/edition-guide")
1694 .emit();
1695 }
1696 }
1697
1698 /// Parses the parameter list and result type of a function declaration.
1699 pub(super) fn parse_fn_decl(
1700 &mut self,
1701 req_name: ReqName,
1702 ret_allow_plus: AllowPlus,
1703 recover_return_sign: RecoverReturnSign,
1704 ) -> PResult<'a, P<FnDecl>> {
1705 Ok(P(FnDecl {
1706 inputs: self.parse_fn_params(req_name)?,
1707 output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?,
1708 }))
1709 }
1710
1711 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1712 fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec<Param>> {
1713 let mut first_param = true;
1714 // Parse the arguments, starting out with `self` being allowed...
1715 let (mut params, _) = self.parse_paren_comma_seq(|p| {
1716 let param = p.parse_param_general(req_name, first_param).or_else(|mut e| {
1717 e.emit();
1718 let lo = p.prev_token.span;
1719 // Skip every token until next possible arg or end.
1720 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1721 // Create a placeholder argument for proper arg count (issue #34264).
1722 Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span))))
1723 });
1724 // ...now that we've parsed the first argument, `self` is no longer allowed.
1725 first_param = false;
1726 param
1727 })?;
1728 // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors.
1729 self.deduplicate_recovered_params_names(&mut params);
1730 Ok(params)
1731 }
1732
1733 /// Parses a single function parameter.
1734 ///
1735 /// - `self` is syntactically allowed when `first_param` holds.
1736 fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> {
1737 let lo = self.token.span;
1738 let attrs = self.parse_outer_attributes()?;
1739
1740 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1741 if let Some(mut param) = self.parse_self_param()? {
1742 param.attrs = attrs.into();
1743 return if first_param { Ok(param) } else { self.recover_bad_self_param(param) };
1744 }
1745
1746 let is_name_required = match self.token.kind {
1747 token::DotDotDot => false,
1748 _ => req_name(self.token.span.edition()),
1749 };
1750 let (pat, ty) = if is_name_required || self.is_named_param() {
1751 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1752
1753 let pat = self.parse_fn_param_pat()?;
1754 if let Err(mut err) = self.expect(&token::Colon) {
1755 return if let Some(ident) =
1756 self.parameter_without_type(&mut err, pat, is_name_required, first_param)
1757 {
1758 err.emit();
1759 Ok(dummy_arg(ident))
1760 } else {
1761 Err(err)
1762 };
1763 }
1764
1765 self.eat_incorrect_doc_comment_for_param_type();
1766 (pat, self.parse_ty_for_param()?)
1767 } else {
1768 debug!("parse_param_general ident_to_pat");
1769 let parser_snapshot_before_ty = self.clone();
1770 self.eat_incorrect_doc_comment_for_param_type();
1771 let mut ty = self.parse_ty_for_param();
1772 if ty.is_ok()
1773 && self.token != token::Comma
1774 && self.token != token::CloseDelim(token::Paren)
1775 {
1776 // This wasn't actually a type, but a pattern looking like a type,
1777 // so we are going to rollback and re-parse for recovery.
1778 ty = self.unexpected();
1779 }
1780 match ty {
1781 Ok(ty) => {
1782 let ident = Ident::new(kw::Empty, self.prev_token.span);
1783 let bm = BindingMode::ByValue(Mutability::Not);
1784 let pat = self.mk_pat_ident(ty.span, bm, ident);
1785 (pat, ty)
1786 }
1787 // If this is a C-variadic argument and we hit an error, return the error.
1788 Err(err) if self.token == token::DotDotDot => return Err(err),
1789 // Recover from attempting to parse the argument as a type without pattern.
1790 Err(mut err) => {
1791 err.cancel();
1792 *self = parser_snapshot_before_ty;
1793 self.recover_arg_parse()?
1794 }
1795 }
1796 };
1797
1798 let span = lo.until(self.token.span);
1799
1800 Ok(Param {
1801 attrs: attrs.into(),
1802 id: ast::DUMMY_NODE_ID,
1803 is_placeholder: false,
1804 pat,
1805 span,
1806 ty,
1807 })
1808 }
1809
1810 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1811 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1812 // Extract an identifier *after* having confirmed that the token is one.
1813 let expect_self_ident = |this: &mut Self| match this.token.ident() {
1814 Some((ident, false)) => {
1815 this.bump();
1816 ident
1817 }
1818 _ => unreachable!(),
1819 };
1820 // Is `self` `n` tokens ahead?
1821 let is_isolated_self = |this: &Self, n| {
1822 this.is_keyword_ahead(n, &[kw::SelfLower])
1823 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1824 };
1825 // Is `mut self` `n` tokens ahead?
1826 let is_isolated_mut_self =
1827 |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1);
1828 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1829 let parse_self_possibly_typed = |this: &mut Self, m| {
1830 let eself_ident = expect_self_ident(this);
1831 let eself_hi = this.prev_token.span;
1832 let eself = if this.eat(&token::Colon) {
1833 SelfKind::Explicit(this.parse_ty()?, m)
1834 } else {
1835 SelfKind::Value(m)
1836 };
1837 Ok((eself, eself_ident, eself_hi))
1838 };
1839 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1840 let recover_self_ptr = |this: &mut Self| {
1841 let msg = "cannot pass `self` by raw pointer";
1842 let span = this.token.span;
1843 this.struct_span_err(span, msg).span_label(span, msg).emit();
1844
1845 Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span))
1846 };
1847
1848 // Parse optional `self` parameter of a method.
1849 // Only a limited set of initial token sequences is considered `self` parameters; anything
1850 // else is parsed as a normal function parameter list, so some lookahead is required.
1851 let eself_lo = self.token.span;
1852 let (eself, eself_ident, eself_hi) = match self.token.uninterpolate().kind {
1853 token::BinOp(token::And) => {
1854 let eself = if is_isolated_self(self, 1) {
1855 // `&self`
1856 self.bump();
1857 SelfKind::Region(None, Mutability::Not)
1858 } else if is_isolated_mut_self(self, 1) {
1859 // `&mut self`
1860 self.bump();
1861 self.bump();
1862 SelfKind::Region(None, Mutability::Mut)
1863 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1864 // `&'lt self`
1865 self.bump();
1866 let lt = self.expect_lifetime();
1867 SelfKind::Region(Some(lt), Mutability::Not)
1868 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1869 // `&'lt mut self`
1870 self.bump();
1871 let lt = self.expect_lifetime();
1872 self.bump();
1873 SelfKind::Region(Some(lt), Mutability::Mut)
1874 } else {
1875 // `&not_self`
1876 return Ok(None);
1877 };
1878 (eself, expect_self_ident(self), self.prev_token.span)
1879 }
1880 // `*self`
1881 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1882 self.bump();
1883 recover_self_ptr(self)?
1884 }
1885 // `*mut self` and `*const self`
1886 token::BinOp(token::Star)
1887 if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) =>
1888 {
1889 self.bump();
1890 self.bump();
1891 recover_self_ptr(self)?
1892 }
1893 // `self` and `self: TYPE`
1894 token::Ident(..) if is_isolated_self(self, 0) => {
1895 parse_self_possibly_typed(self, Mutability::Not)?
1896 }
1897 // `mut self` and `mut self: TYPE`
1898 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1899 self.bump();
1900 parse_self_possibly_typed(self, Mutability::Mut)?
1901 }
1902 _ => return Ok(None),
1903 };
1904
1905 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1906 Ok(Some(Param::from_self(AttrVec::default(), eself, eself_ident)))
1907 }
1908
1909 fn is_named_param(&self) -> bool {
1910 let offset = match self.token.kind {
1911 token::Interpolated(ref nt) => match **nt {
1912 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1913 _ => 0,
1914 },
1915 token::BinOp(token::And) | token::AndAnd => 1,
1916 _ if self.token.is_keyword(kw::Mut) => 1,
1917 _ => 0,
1918 };
1919
1920 self.look_ahead(offset, |t| t.is_ident())
1921 && self.look_ahead(offset + 1, |t| t == &token::Colon)
1922 }
1923
1924 fn recover_first_param(&mut self) -> &'static str {
1925 match self
1926 .parse_outer_attributes()
1927 .and_then(|_| self.parse_self_param())
1928 .map_err(|mut e| e.cancel())
1929 {
1930 Ok(Some(_)) => "method",
1931 _ => "function",
1932 }
1933 }
1934 }