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