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