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