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