]>
Commit | Line | Data |
---|---|---|
74b04a01 | 1 | use super::{Parser, PathStyle, TokenType}; |
416331ca | 2 | |
dfeec247 | 3 | use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; |
416331ca | 4 | |
74b04a01 XL |
5 | use rustc_ast::ptr::P; |
6 | use rustc_ast::token::{self, Token, TokenKind}; | |
3c0e092e XL |
7 | use rustc_ast::{ |
8 | self as ast, BareFnTy, FnRetTy, GenericBound, GenericBounds, GenericParam, Generics, Lifetime, | |
9 | MacCall, MutTy, Mutability, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax, Ty, TyKind, | |
10 | }; | |
dfeec247 XL |
11 | use rustc_errors::{pluralize, struct_span_err, Applicability, PResult}; |
12 | use rustc_span::source_map::Span; | |
13 | use rustc_span::symbol::{kw, sym}; | |
dfeec247 | 14 | |
94222f64 | 15 | /// Any `?` or `~const` modifiers that appear at the start of a bound. |
dfeec247 XL |
16 | struct BoundModifiers { |
17 | /// `?Trait`. | |
18 | maybe: Option<Span>, | |
19 | ||
94222f64 | 20 | /// `~const Trait`. |
dfeec247 XL |
21 | maybe_const: Option<Span>, |
22 | } | |
23 | ||
24 | impl BoundModifiers { | |
25 | fn to_trait_bound_modifier(&self) -> TraitBoundModifier { | |
26 | match (self.maybe, self.maybe_const) { | |
27 | (None, None) => TraitBoundModifier::None, | |
28 | (Some(_), None) => TraitBoundModifier::Maybe, | |
29 | (None, Some(_)) => TraitBoundModifier::MaybeConst, | |
30 | (Some(_), Some(_)) => TraitBoundModifier::MaybeConstMaybe, | |
31 | } | |
32 | } | |
33 | } | |
416331ca | 34 | |
74b04a01 XL |
35 | #[derive(Copy, Clone, PartialEq)] |
36 | pub(super) enum AllowPlus { | |
37 | Yes, | |
38 | No, | |
39 | } | |
40 | ||
41 | #[derive(PartialEq)] | |
42 | pub(super) enum RecoverQPath { | |
43 | Yes, | |
44 | No, | |
45 | } | |
46 | ||
fc512014 XL |
47 | /// Signals whether parsing a type should recover `->`. |
48 | /// | |
49 | /// More specifically, when parsing a function like: | |
50 | /// ```rust | |
51 | /// fn foo() => u8 { 0 } | |
52 | /// fn bar(): u8 { 0 } | |
53 | /// ``` | |
54 | /// The compiler will try to recover interpreting `foo() => u8` as `foo() -> u8` when calling | |
55 | /// `parse_ty` with anything except `RecoverReturnSign::No`, and it will try to recover `bar(): u8` | |
56 | /// as `bar() -> u8` when passing `RecoverReturnSign::Yes` to `parse_ty` | |
57 | #[derive(Copy, Clone, PartialEq)] | |
58 | pub(super) enum RecoverReturnSign { | |
59 | Yes, | |
60 | OnlyFatArrow, | |
61 | No, | |
62 | } | |
63 | ||
64 | impl RecoverReturnSign { | |
65 | /// [RecoverReturnSign::Yes] allows for recovering `fn foo() => u8` and `fn foo(): u8`, | |
66 | /// [RecoverReturnSign::OnlyFatArrow] allows for recovering only `fn foo() => u8` (recovering | |
67 | /// colons can cause problems when parsing where clauses), and | |
68 | /// [RecoverReturnSign::No] doesn't allow for any recovery of the return type arrow | |
69 | fn can_recover(self, token: &TokenKind) -> bool { | |
70 | match self { | |
71 | Self::Yes => matches!(token, token::FatArrow | token::Colon), | |
72 | Self::OnlyFatArrow => matches!(token, token::FatArrow), | |
73 | Self::No => false, | |
74 | } | |
75 | } | |
76 | } | |
77 | ||
74b04a01 XL |
78 | // Is `...` (`CVarArgs`) legal at this level of type parsing? |
79 | #[derive(PartialEq)] | |
80 | enum AllowCVariadic { | |
81 | Yes, | |
82 | No, | |
83 | } | |
84 | ||
416331ca XL |
85 | /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`, |
86 | /// `IDENT<<u8 as Trait>::AssocTy>`. | |
87 | /// | |
88 | /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes | |
89 | /// that `IDENT` is not the ident of a fn trait. | |
90 | fn can_continue_type_after_non_fn_ident(t: &Token) -> bool { | |
dfeec247 | 91 | t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl) |
416331ca XL |
92 | } |
93 | ||
94 | impl<'a> Parser<'a> { | |
95 | /// Parses a type. | |
96 | pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> { | |
fc512014 XL |
97 | self.parse_ty_common( |
98 | AllowPlus::Yes, | |
99 | AllowCVariadic::No, | |
100 | RecoverQPath::Yes, | |
101 | RecoverReturnSign::Yes, | |
3c0e092e XL |
102 | None, |
103 | ) | |
104 | } | |
105 | ||
106 | pub(super) fn parse_ty_with_generics_recovery( | |
107 | &mut self, | |
108 | ty_params: &Generics, | |
109 | ) -> PResult<'a, P<Ty>> { | |
110 | self.parse_ty_common( | |
111 | AllowPlus::Yes, | |
112 | AllowCVariadic::No, | |
113 | RecoverQPath::Yes, | |
114 | RecoverReturnSign::Yes, | |
115 | Some(ty_params), | |
fc512014 | 116 | ) |
416331ca XL |
117 | } |
118 | ||
dfeec247 XL |
119 | /// Parse a type suitable for a function or function pointer parameter. |
120 | /// The difference from `parse_ty` is that this version allows `...` | |
1b1a35ee | 121 | /// (`CVarArgs`) at the top level of the type. |
dfeec247 | 122 | pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> { |
fc512014 XL |
123 | self.parse_ty_common( |
124 | AllowPlus::Yes, | |
125 | AllowCVariadic::Yes, | |
126 | RecoverQPath::Yes, | |
127 | RecoverReturnSign::Yes, | |
3c0e092e | 128 | None, |
fc512014 | 129 | ) |
dfeec247 XL |
130 | } |
131 | ||
416331ca XL |
132 | /// Parses a type in restricted contexts where `+` is not permitted. |
133 | /// | |
134 | /// Example 1: `&'a TYPE` | |
135 | /// `+` is prohibited to maintain operator priority (P(+) < P(&)). | |
136 | /// Example 2: `value1 as TYPE + value2` | |
137 | /// `+` is prohibited to avoid interactions with expression grammar. | |
138 | pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> { | |
fc512014 XL |
139 | self.parse_ty_common( |
140 | AllowPlus::No, | |
141 | AllowCVariadic::No, | |
142 | RecoverQPath::Yes, | |
143 | RecoverReturnSign::Yes, | |
3c0e092e | 144 | None, |
fc512014 XL |
145 | ) |
146 | } | |
147 | ||
148 | /// Parse a type without recovering `:` as `->` to avoid breaking code such as `where fn() : for<'a>` | |
149 | pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, P<Ty>> { | |
150 | self.parse_ty_common( | |
151 | AllowPlus::Yes, | |
152 | AllowCVariadic::Yes, | |
153 | RecoverQPath::Yes, | |
154 | RecoverReturnSign::OnlyFatArrow, | |
3c0e092e | 155 | None, |
fc512014 | 156 | ) |
416331ca XL |
157 | } |
158 | ||
159 | /// Parses an optional return type `[ -> TY ]` in a function declaration. | |
dfeec247 XL |
160 | pub(super) fn parse_ret_ty( |
161 | &mut self, | |
74b04a01 XL |
162 | allow_plus: AllowPlus, |
163 | recover_qpath: RecoverQPath, | |
fc512014 | 164 | recover_return_sign: RecoverReturnSign, |
74b04a01 | 165 | ) -> PResult<'a, FnRetTy> { |
dfeec247 XL |
166 | Ok(if self.eat(&token::RArrow) { |
167 | // FIXME(Centril): Can we unconditionally `allow_plus`? | |
fc512014 XL |
168 | let ty = self.parse_ty_common( |
169 | allow_plus, | |
170 | AllowCVariadic::No, | |
171 | recover_qpath, | |
172 | recover_return_sign, | |
3c0e092e | 173 | None, |
fc512014 XL |
174 | )?; |
175 | FnRetTy::Ty(ty) | |
176 | } else if recover_return_sign.can_recover(&self.token.kind) { | |
177 | // Don't `eat` to prevent `=>` from being added as an expected token which isn't | |
178 | // actually expected and could only confuse users | |
179 | self.bump(); | |
180 | self.struct_span_err(self.prev_token.span, "return types are denoted using `->`") | |
181 | .span_suggestion_short( | |
182 | self.prev_token.span, | |
183 | "use `->` instead", | |
184 | "->".to_string(), | |
185 | Applicability::MachineApplicable, | |
186 | ) | |
187 | .emit(); | |
188 | let ty = self.parse_ty_common( | |
189 | allow_plus, | |
190 | AllowCVariadic::No, | |
191 | recover_qpath, | |
192 | recover_return_sign, | |
3c0e092e | 193 | None, |
fc512014 | 194 | )?; |
74b04a01 | 195 | FnRetTy::Ty(ty) |
416331ca | 196 | } else { |
74b04a01 | 197 | FnRetTy::Default(self.token.span.shrink_to_lo()) |
dfeec247 | 198 | }) |
416331ca XL |
199 | } |
200 | ||
dfeec247 XL |
201 | fn parse_ty_common( |
202 | &mut self, | |
74b04a01 | 203 | allow_plus: AllowPlus, |
74b04a01 | 204 | allow_c_variadic: AllowCVariadic, |
fc512014 XL |
205 | recover_qpath: RecoverQPath, |
206 | recover_return_sign: RecoverReturnSign, | |
3c0e092e | 207 | ty_generics: Option<&Generics>, |
dfeec247 | 208 | ) -> PResult<'a, P<Ty>> { |
74b04a01 | 209 | let allow_qpath_recovery = recover_qpath == RecoverQPath::Yes; |
416331ca XL |
210 | maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery); |
211 | maybe_whole!(self, NtTy, |x| x); | |
212 | ||
213 | let lo = self.token.span; | |
214 | let mut impl_dyn_multi = false; | |
dfeec247 XL |
215 | let kind = if self.check(&token::OpenDelim(token::Paren)) { |
216 | self.parse_ty_tuple_or_parens(lo, allow_plus)? | |
416331ca XL |
217 | } else if self.eat(&token::Not) { |
218 | // Never type `!` | |
219 | TyKind::Never | |
220 | } else if self.eat(&token::BinOp(token::Star)) { | |
dfeec247 | 221 | self.parse_ty_ptr()? |
416331ca | 222 | } else if self.eat(&token::OpenDelim(token::Bracket)) { |
dfeec247 | 223 | self.parse_array_or_slice_ty()? |
416331ca XL |
224 | } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) { |
225 | // Reference | |
226 | self.expect_and()?; | |
227 | self.parse_borrowed_pointee()? | |
228 | } else if self.eat_keyword_noexpect(kw::Typeof) { | |
dfeec247 | 229 | self.parse_typeof_ty()? |
416331ca XL |
230 | } else if self.eat_keyword(kw::Underscore) { |
231 | // A type to be inferred `_` | |
232 | TyKind::Infer | |
6a06907d | 233 | } else if self.check_fn_front_matter(false) { |
416331ca | 234 | // Function pointer type |
fc512014 | 235 | self.parse_ty_bare_fn(lo, Vec::new(), recover_return_sign)? |
416331ca XL |
236 | } else if self.check_keyword(kw::For) { |
237 | // Function pointer type or bound list (trait object type) starting with a poly-trait. | |
238 | // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T` | |
239 | // `for<'lt> Trait1<'lt> + Trait2 + 'a` | |
416331ca | 240 | let lifetime_defs = self.parse_late_bound_lifetime_defs()?; |
6a06907d | 241 | if self.check_fn_front_matter(false) { |
fc512014 | 242 | self.parse_ty_bare_fn(lo, lifetime_defs, recover_return_sign)? |
416331ca XL |
243 | } else { |
244 | let path = self.parse_path(PathStyle::Type)?; | |
74b04a01 | 245 | let parse_plus = allow_plus == AllowPlus::Yes && self.check_plus(); |
ba9703b0 | 246 | self.parse_remaining_bounds_path(lifetime_defs, path, lo, parse_plus)? |
416331ca XL |
247 | } |
248 | } else if self.eat_keyword(kw::Impl) { | |
dfeec247 XL |
249 | self.parse_impl_ty(&mut impl_dyn_multi)? |
250 | } else if self.is_explicit_dyn_type() { | |
251 | self.parse_dyn_ty(&mut impl_dyn_multi)? | |
416331ca XL |
252 | } else if self.eat_lt() { |
253 | // Qualified path | |
254 | let (qself, path) = self.parse_qpath(PathStyle::Type)?; | |
255 | TyKind::Path(Some(qself), path) | |
ba9703b0 | 256 | } else if self.check_path() { |
3c0e092e | 257 | self.parse_path_start_ty(lo, allow_plus, ty_generics)? |
ba9703b0 XL |
258 | } else if self.can_begin_bound() { |
259 | self.parse_bare_trait_object(lo, allow_plus)? | |
dfeec247 | 260 | } else if self.eat(&token::DotDotDot) { |
74b04a01 | 261 | if allow_c_variadic == AllowCVariadic::Yes { |
416331ca XL |
262 | TyKind::CVarArgs |
263 | } else { | |
dfeec247 XL |
264 | // FIXME(Centril): Should we just allow `...` syntactically |
265 | // anywhere in a type and use semantic restrictions instead? | |
266 | self.error_illegal_c_varadic_ty(lo); | |
267 | TyKind::Err | |
416331ca XL |
268 | } |
269 | } else { | |
dfeec247 XL |
270 | let msg = format!("expected type, found {}", super::token_descr(&self.token)); |
271 | let mut err = self.struct_span_err(self.token.span, &msg); | |
416331ca XL |
272 | err.span_label(self.token.span, "expected type"); |
273 | self.maybe_annotate_with_ascription(&mut err, true); | |
274 | return Err(err); | |
275 | }; | |
276 | ||
74b04a01 | 277 | let span = lo.to(self.prev_token.span); |
e74abb32 | 278 | let ty = self.mk_ty(span, kind); |
416331ca XL |
279 | |
280 | // Try to recover from use of `+` with incorrect priority. | |
281 | self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty); | |
282 | self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?; | |
283 | self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery) | |
284 | } | |
285 | ||
dfeec247 XL |
286 | /// Parses either: |
287 | /// - `(TYPE)`, a parenthesized type. | |
288 | /// - `(TYPE,)`, a tuple with a single field of type TYPE. | |
74b04a01 | 289 | fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> { |
dfeec247 XL |
290 | let mut trailing_plus = false; |
291 | let (ts, trailing) = self.parse_paren_comma_seq(|p| { | |
292 | let ty = p.parse_ty()?; | |
74b04a01 | 293 | trailing_plus = p.prev_token.kind == TokenKind::BinOp(token::Plus); |
dfeec247 XL |
294 | Ok(ty) |
295 | })?; | |
296 | ||
297 | if ts.len() == 1 && !trailing { | |
74b04a01 XL |
298 | let ty = ts.into_iter().next().unwrap().into_inner(); |
299 | let maybe_bounds = allow_plus == AllowPlus::Yes && self.token.is_like_plus(); | |
dfeec247 XL |
300 | match ty.kind { |
301 | // `(TY_BOUND_NOPAREN) + BOUND + ...`. | |
302 | TyKind::Path(None, path) if maybe_bounds => { | |
ba9703b0 | 303 | self.parse_remaining_bounds_path(Vec::new(), path, lo, true) |
dfeec247 | 304 | } |
ba9703b0 | 305 | TyKind::TraitObject(bounds, TraitObjectSyntax::None) |
dfeec247 XL |
306 | if maybe_bounds && bounds.len() == 1 && !trailing_plus => |
307 | { | |
ba9703b0 | 308 | self.parse_remaining_bounds(bounds, true) |
dfeec247 XL |
309 | } |
310 | // `(TYPE)` | |
311 | _ => Ok(TyKind::Paren(P(ty))), | |
312 | } | |
313 | } else { | |
314 | Ok(TyKind::Tup(ts)) | |
315 | } | |
316 | } | |
317 | ||
ba9703b0 XL |
318 | fn parse_bare_trait_object(&mut self, lo: Span, allow_plus: AllowPlus) -> PResult<'a, TyKind> { |
319 | let lt_no_plus = self.check_lifetime() && !self.look_ahead(1, |t| t.is_like_plus()); | |
320 | let bounds = self.parse_generic_bounds_common(allow_plus, None)?; | |
321 | if lt_no_plus { | |
322 | self.struct_span_err(lo, "lifetime in trait object type must be followed by `+`").emit() | |
323 | } | |
324 | Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None)) | |
325 | } | |
326 | ||
327 | fn parse_remaining_bounds_path( | |
dfeec247 XL |
328 | &mut self, |
329 | generic_params: Vec<GenericParam>, | |
330 | path: ast::Path, | |
331 | lo: Span, | |
332 | parse_plus: bool, | |
333 | ) -> PResult<'a, TyKind> { | |
74b04a01 | 334 | let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_token.span)); |
ba9703b0 XL |
335 | let bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)]; |
336 | self.parse_remaining_bounds(bounds, parse_plus) | |
337 | } | |
338 | ||
339 | /// Parse the remainder of a bare trait object type given an already parsed list. | |
340 | fn parse_remaining_bounds( | |
341 | &mut self, | |
342 | mut bounds: GenericBounds, | |
343 | plus: bool, | |
344 | ) -> PResult<'a, TyKind> { | |
ba9703b0 | 345 | if plus { |
416331ca | 346 | self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded |
74b04a01 | 347 | bounds.append(&mut self.parse_generic_bounds(Some(self.prev_token.span))?); |
416331ca XL |
348 | } |
349 | Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None)) | |
350 | } | |
351 | ||
dfeec247 XL |
352 | /// Parses a raw pointer type: `*[const | mut] $type`. |
353 | fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> { | |
e74abb32 | 354 | let mutbl = self.parse_const_or_mut().unwrap_or_else(|| { |
74b04a01 | 355 | let span = self.prev_token.span; |
416331ca XL |
356 | let msg = "expected mut or const in raw pointer type"; |
357 | self.struct_span_err(span, msg) | |
358 | .span_label(span, msg) | |
359 | .help("use `*mut T` or `*const T` as appropriate") | |
360 | .emit(); | |
dfeec247 | 361 | Mutability::Not |
e74abb32 | 362 | }); |
dfeec247 XL |
363 | let ty = self.parse_ty_no_plus()?; |
364 | Ok(TyKind::Ptr(MutTy { ty, mutbl })) | |
416331ca XL |
365 | } |
366 | ||
dfeec247 XL |
367 | /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type. |
368 | /// The opening `[` bracket is already eaten. | |
369 | fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> { | |
29967ef6 XL |
370 | let elt_ty = match self.parse_ty() { |
371 | Ok(ty) => ty, | |
372 | Err(mut err) | |
373 | if self.look_ahead(1, |t| t.kind == token::CloseDelim(token::Bracket)) | |
374 | | self.look_ahead(1, |t| t.kind == token::Semi) => | |
375 | { | |
376 | // Recover from `[LIT; EXPR]` and `[LIT]` | |
377 | self.bump(); | |
378 | err.emit(); | |
379 | self.mk_ty(self.prev_token.span, TyKind::Err) | |
380 | } | |
381 | Err(err) => return Err(err), | |
382 | }; | |
6a06907d | 383 | |
dfeec247 | 384 | let ty = if self.eat(&token::Semi) { |
6a06907d XL |
385 | let mut length = self.parse_anon_const_expr()?; |
386 | if let Err(e) = self.expect(&token::CloseDelim(token::Bracket)) { | |
387 | // Try to recover from `X<Y, ...>` when `X::<Y, ...>` works | |
388 | self.check_mistyped_turbofish_with_multiple_type_params(e, &mut length.value)?; | |
389 | self.expect(&token::CloseDelim(token::Bracket))?; | |
390 | } | |
391 | TyKind::Array(elt_ty, length) | |
416331ca | 392 | } else { |
6a06907d | 393 | self.expect(&token::CloseDelim(token::Bracket))?; |
dfeec247 XL |
394 | TyKind::Slice(elt_ty) |
395 | }; | |
6a06907d | 396 | |
dfeec247 | 397 | Ok(ty) |
416331ca XL |
398 | } |
399 | ||
400 | fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> { | |
1b1a35ee XL |
401 | let and_span = self.prev_token.span; |
402 | let mut opt_lifetime = | |
403 | if self.check_lifetime() { Some(self.expect_lifetime()) } else { None }; | |
136023e0 | 404 | let mut mutbl = self.parse_mutability(); |
1b1a35ee XL |
405 | if self.token.is_lifetime() && mutbl == Mutability::Mut && opt_lifetime.is_none() { |
406 | // A lifetime is invalid here: it would be part of a bare trait bound, which requires | |
407 | // it to be followed by a plus, but we disallow plus in the pointee type. | |
408 | // So we can handle this case as an error here, and suggest `'a mut`. | |
409 | // If there *is* a plus next though, handling the error later provides better suggestions | |
410 | // (like adding parentheses) | |
411 | if !self.look_ahead(1, |t| t.is_like_plus()) { | |
412 | let lifetime_span = self.token.span; | |
413 | let span = and_span.to(lifetime_span); | |
414 | ||
415 | let mut err = self.struct_span_err(span, "lifetime must precede `mut`"); | |
416 | if let Ok(lifetime_src) = self.span_to_snippet(lifetime_span) { | |
417 | err.span_suggestion( | |
418 | span, | |
419 | "place the lifetime before `mut`", | |
420 | format!("&{} mut", lifetime_src), | |
421 | Applicability::MaybeIncorrect, | |
422 | ); | |
423 | } | |
424 | err.emit(); | |
425 | ||
426 | opt_lifetime = Some(self.expect_lifetime()); | |
427 | } | |
136023e0 XL |
428 | } else if self.token.is_keyword(kw::Dyn) |
429 | && mutbl == Mutability::Not | |
430 | && self.look_ahead(1, |t| t.is_keyword(kw::Mut)) | |
431 | { | |
432 | // We have `&dyn mut ...`, which is invalid and should be `&mut dyn ...`. | |
433 | let span = and_span.to(self.look_ahead(1, |t| t.span)); | |
434 | let mut err = self.struct_span_err(span, "`mut` must precede `dyn`"); | |
435 | err.span_suggestion( | |
436 | span, | |
437 | "place `mut` before `dyn`", | |
438 | "&mut dyn".to_string(), | |
439 | Applicability::MachineApplicable, | |
440 | ); | |
441 | err.emit(); | |
442 | ||
443 | // Recovery | |
444 | mutbl = Mutability::Mut; | |
445 | let (dyn_tok, dyn_tok_sp) = (self.token.clone(), self.token_spacing); | |
446 | self.bump(); | |
447 | self.bump_with((dyn_tok, dyn_tok_sp)); | |
1b1a35ee | 448 | } |
416331ca | 449 | let ty = self.parse_ty_no_plus()?; |
dfeec247 XL |
450 | Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl })) |
451 | } | |
452 | ||
453 | // Parses the `typeof(EXPR)`. | |
3c0e092e | 454 | // To avoid ambiguity, the type is surrounded by parentheses. |
dfeec247 XL |
455 | fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> { |
456 | self.expect(&token::OpenDelim(token::Paren))?; | |
457 | let expr = self.parse_anon_const_expr()?; | |
458 | self.expect(&token::CloseDelim(token::Paren))?; | |
459 | Ok(TyKind::Typeof(expr)) | |
416331ca XL |
460 | } |
461 | ||
dfeec247 XL |
462 | /// Parses a function pointer type (`TyKind::BareFn`). |
463 | /// ``` | |
464 | /// [unsafe] [extern "ABI"] fn (S) -> T | |
465 | /// ^~~~~^ ^~~~^ ^~^ ^ | |
466 | /// | | | | | |
467 | /// | | | Return type | |
468 | /// Function Style ABI Parameter types | |
469 | /// ``` | |
ba9703b0 | 470 | /// We actually parse `FnHeader FnDecl`, but we error on `const` and `async` qualifiers. |
fc512014 XL |
471 | fn parse_ty_bare_fn( |
472 | &mut self, | |
473 | lo: Span, | |
474 | params: Vec<GenericParam>, | |
475 | recover_return_sign: RecoverReturnSign, | |
476 | ) -> PResult<'a, TyKind> { | |
a2a8927a XL |
477 | let inherited_vis = rustc_ast::Visibility { |
478 | span: rustc_span::DUMMY_SP, | |
479 | kind: rustc_ast::VisibilityKind::Inherited, | |
480 | tokens: None, | |
481 | }; | |
482 | let ast::FnHeader { ext, unsafety, constness, asyncness } = | |
483 | self.parse_fn_front_matter(&inherited_vis)?; | |
fc512014 | 484 | let decl = self.parse_fn_decl(|_| false, AllowPlus::No, recover_return_sign)?; |
ba9703b0 XL |
485 | let whole_span = lo.to(self.prev_token.span); |
486 | if let ast::Const::Yes(span) = constness { | |
487 | self.error_fn_ptr_bad_qualifier(whole_span, span, "const"); | |
488 | } | |
489 | if let ast::Async::Yes { span, .. } = asyncness { | |
490 | self.error_fn_ptr_bad_qualifier(whole_span, span, "async"); | |
491 | } | |
492 | Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params: params, decl }))) | |
493 | } | |
494 | ||
495 | /// Emit an error for the given bad function pointer qualifier. | |
496 | fn error_fn_ptr_bad_qualifier(&self, span: Span, qual_span: Span, qual: &str) { | |
497 | self.struct_span_err(span, &format!("an `fn` pointer type cannot be `{}`", qual)) | |
498 | .span_label(qual_span, format!("`{}` because of this", qual)) | |
499 | .span_suggestion_short( | |
500 | qual_span, | |
501 | &format!("remove the `{}` qualifier", qual), | |
502 | String::new(), | |
503 | Applicability::MaybeIncorrect, | |
504 | ) | |
505 | .emit(); | |
dfeec247 XL |
506 | } |
507 | ||
508 | /// Parses an `impl B0 + ... + Bn` type. | |
509 | fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> { | |
510 | // Always parse bounds greedily for better error recovery. | |
511 | let bounds = self.parse_generic_bounds(None)?; | |
74b04a01 | 512 | *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus); |
dfeec247 XL |
513 | Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)) |
514 | } | |
515 | ||
516 | /// Is a `dyn B0 + ... + Bn` type allowed here? | |
517 | fn is_explicit_dyn_type(&mut self) -> bool { | |
518 | self.check_keyword(kw::Dyn) | |
17df50a5 | 519 | && (!self.token.uninterpolated_span().rust_2015() |
dfeec247 XL |
520 | || self.look_ahead(1, |t| { |
521 | t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t) | |
522 | })) | |
523 | } | |
524 | ||
525 | /// Parses a `dyn B0 + ... + Bn` type. | |
526 | /// | |
527 | /// Note that this does *not* parse bare trait objects. | |
528 | fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> { | |
529 | self.bump(); // `dyn` | |
530 | // Always parse bounds greedily for better error recovery. | |
531 | let bounds = self.parse_generic_bounds(None)?; | |
74b04a01 | 532 | *impl_dyn_multi = bounds.len() > 1 || self.prev_token.kind == TokenKind::BinOp(token::Plus); |
dfeec247 | 533 | Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)) |
416331ca XL |
534 | } |
535 | ||
dfeec247 XL |
536 | /// Parses a type starting with a path. |
537 | /// | |
538 | /// This can be: | |
539 | /// 1. a type macro, `mac!(...)`, | |
540 | /// 2. a bare trait object, `B0 + ... + Bn`, | |
541 | /// 3. or a path, `path::to::MyType`. | |
3c0e092e XL |
542 | fn parse_path_start_ty( |
543 | &mut self, | |
544 | lo: Span, | |
545 | allow_plus: AllowPlus, | |
546 | ty_generics: Option<&Generics>, | |
547 | ) -> PResult<'a, TyKind> { | |
dfeec247 | 548 | // Simple path |
3c0e092e | 549 | let path = self.parse_path_inner(PathStyle::Type, ty_generics)?; |
dfeec247 XL |
550 | if self.eat(&token::Not) { |
551 | // Macro invocation in type position | |
ba9703b0 | 552 | Ok(TyKind::MacCall(MacCall { |
dfeec247 XL |
553 | path, |
554 | args: self.parse_mac_args()?, | |
555 | prior_type_ascription: self.last_type_ascription, | |
556 | })) | |
74b04a01 | 557 | } else if allow_plus == AllowPlus::Yes && self.check_plus() { |
dfeec247 | 558 | // `Trait1 + Trait2 + 'a` |
ba9703b0 | 559 | self.parse_remaining_bounds_path(Vec::new(), path, lo, true) |
dfeec247 XL |
560 | } else { |
561 | // Just a type path. | |
562 | Ok(TyKind::Path(None, path)) | |
563 | } | |
564 | } | |
565 | ||
566 | fn error_illegal_c_varadic_ty(&self, lo: Span) { | |
567 | struct_span_err!( | |
568 | self.sess.span_diagnostic, | |
74b04a01 | 569 | lo.to(self.prev_token.span), |
dfeec247 XL |
570 | E0743, |
571 | "C-variadic type `...` may not be nested inside another type", | |
572 | ) | |
573 | .emit(); | |
574 | } | |
575 | ||
576 | pub(super) fn parse_generic_bounds( | |
577 | &mut self, | |
578 | colon_span: Option<Span>, | |
579 | ) -> PResult<'a, GenericBounds> { | |
74b04a01 | 580 | self.parse_generic_bounds_common(AllowPlus::Yes, colon_span) |
416331ca XL |
581 | } |
582 | ||
583 | /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`. | |
584 | /// | |
dfeec247 XL |
585 | /// See `parse_generic_bound` for the `BOUND` grammar. |
586 | fn parse_generic_bounds_common( | |
587 | &mut self, | |
74b04a01 | 588 | allow_plus: AllowPlus, |
dfeec247 XL |
589 | colon_span: Option<Span>, |
590 | ) -> PResult<'a, GenericBounds> { | |
416331ca XL |
591 | let mut bounds = Vec::new(); |
592 | let mut negative_bounds = Vec::new(); | |
17df50a5 XL |
593 | |
594 | while self.can_begin_bound() || self.token.is_keyword(kw::Dyn) { | |
595 | if self.token.is_keyword(kw::Dyn) { | |
596 | // Account for `&dyn Trait + dyn Other`. | |
597 | self.struct_span_err(self.token.span, "invalid `dyn` keyword") | |
598 | .help("`dyn` is only needed at the start of a trait `+`-separated list") | |
599 | .span_suggestion( | |
600 | self.token.span, | |
601 | "remove this keyword", | |
602 | String::new(), | |
603 | Applicability::MachineApplicable, | |
604 | ) | |
605 | .emit(); | |
606 | self.bump(); | |
607 | } | |
dfeec247 XL |
608 | match self.parse_generic_bound()? { |
609 | Ok(bound) => bounds.push(bound), | |
610 | Err(neg_sp) => negative_bounds.push(neg_sp), | |
416331ca | 611 | } |
74b04a01 | 612 | if allow_plus == AllowPlus::No || !self.eat_plus() { |
dfeec247 | 613 | break; |
416331ca XL |
614 | } |
615 | } | |
616 | ||
dfeec247 XL |
617 | if !negative_bounds.is_empty() { |
618 | self.error_negative_bounds(colon_span, &bounds, negative_bounds); | |
619 | } | |
620 | ||
621 | Ok(bounds) | |
622 | } | |
623 | ||
624 | /// Can the current token begin a bound? | |
625 | fn can_begin_bound(&mut self) -> bool { | |
626 | // This needs to be synchronized with `TokenKind::can_begin_bound`. | |
627 | self.check_path() | |
628 | || self.check_lifetime() | |
629 | || self.check(&token::Not) // Used for error reporting only. | |
630 | || self.check(&token::Question) | |
94222f64 | 631 | || self.check(&token::Tilde) |
dfeec247 XL |
632 | || self.check_keyword(kw::For) |
633 | || self.check(&token::OpenDelim(token::Paren)) | |
634 | } | |
635 | ||
636 | fn error_negative_bounds( | |
637 | &self, | |
638 | colon_span: Option<Span>, | |
639 | bounds: &[GenericBound], | |
640 | negative_bounds: Vec<Span>, | |
641 | ) { | |
642 | let negative_bounds_len = negative_bounds.len(); | |
643 | let last_span = *negative_bounds.last().expect("no negative bounds, but still error?"); | |
644 | let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported"); | |
645 | err.span_label(last_span, "negative bounds are not supported"); | |
646 | if let Some(bound_list) = colon_span { | |
74b04a01 | 647 | let bound_list = bound_list.to(self.prev_token.span); |
dfeec247 XL |
648 | let mut new_bound_list = String::new(); |
649 | if !bounds.is_empty() { | |
650 | let mut snippets = bounds.iter().map(|bound| self.span_to_snippet(bound.span())); | |
651 | while let Some(Ok(snippet)) = snippets.next() { | |
652 | new_bound_list.push_str(" + "); | |
653 | new_bound_list.push_str(&snippet); | |
416331ca | 654 | } |
dfeec247 | 655 | new_bound_list = new_bound_list.replacen(" +", ":", 1); |
416331ca | 656 | } |
dfeec247 XL |
657 | err.tool_only_span_suggestion( |
658 | bound_list, | |
659 | &format!("remove the bound{}", pluralize!(negative_bounds_len)), | |
660 | new_bound_list, | |
661 | Applicability::MachineApplicable, | |
662 | ); | |
663 | } | |
664 | err.emit(); | |
665 | } | |
666 | ||
667 | /// Parses a bound according to the grammar: | |
668 | /// ``` | |
669 | /// BOUND = TY_BOUND | LT_BOUND | |
670 | /// ``` | |
671 | fn parse_generic_bound(&mut self) -> PResult<'a, Result<GenericBound, Span>> { | |
74b04a01 | 672 | let anchor_lo = self.prev_token.span; |
dfeec247 XL |
673 | let lo = self.token.span; |
674 | let has_parens = self.eat(&token::OpenDelim(token::Paren)); | |
675 | let inner_lo = self.token.span; | |
676 | let is_negative = self.eat(&token::Not); | |
677 | ||
94222f64 | 678 | let modifiers = self.parse_ty_bound_modifiers()?; |
dfeec247 XL |
679 | let bound = if self.token.is_lifetime() { |
680 | self.error_lt_bound_with_modifiers(modifiers); | |
681 | self.parse_generic_lt_bound(lo, inner_lo, has_parens)? | |
682 | } else { | |
683 | self.parse_generic_ty_bound(lo, has_parens, modifiers)? | |
684 | }; | |
685 | ||
74b04a01 | 686 | Ok(if is_negative { Err(anchor_lo.to(self.prev_token.span)) } else { Ok(bound) }) |
dfeec247 XL |
687 | } |
688 | ||
689 | /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to: | |
690 | /// ``` | |
691 | /// LT_BOUND = LIFETIME | |
692 | /// ``` | |
693 | fn parse_generic_lt_bound( | |
694 | &mut self, | |
695 | lo: Span, | |
696 | inner_lo: Span, | |
697 | has_parens: bool, | |
698 | ) -> PResult<'a, GenericBound> { | |
699 | let bound = GenericBound::Outlives(self.expect_lifetime()); | |
700 | if has_parens { | |
701 | // FIXME(Centril): Consider not erroring here and accepting `('lt)` instead, | |
702 | // possibly introducing `GenericBound::Paren(P<GenericBound>)`? | |
703 | self.recover_paren_lifetime(lo, inner_lo)?; | |
704 | } | |
705 | Ok(bound) | |
706 | } | |
707 | ||
708 | /// Emits an error if any trait bound modifiers were present. | |
709 | fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) { | |
710 | if let Some(span) = modifiers.maybe_const { | |
711 | self.struct_span_err( | |
712 | span, | |
94222f64 | 713 | "`~const` may only modify trait bounds, not lifetime bounds", |
dfeec247 XL |
714 | ) |
715 | .emit(); | |
716 | } | |
717 | ||
718 | if let Some(span) = modifiers.maybe { | |
719 | self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds") | |
720 | .emit(); | |
721 | } | |
722 | } | |
723 | ||
724 | /// Recover on `('lifetime)` with `(` already eaten. | |
725 | fn recover_paren_lifetime(&mut self, lo: Span, inner_lo: Span) -> PResult<'a, ()> { | |
74b04a01 | 726 | let inner_span = inner_lo.to(self.prev_token.span); |
dfeec247 XL |
727 | self.expect(&token::CloseDelim(token::Paren))?; |
728 | let mut err = self.struct_span_err( | |
74b04a01 | 729 | lo.to(self.prev_token.span), |
dfeec247 XL |
730 | "parenthesized lifetime bounds are not supported", |
731 | ); | |
732 | if let Ok(snippet) = self.span_to_snippet(inner_span) { | |
733 | err.span_suggestion_short( | |
74b04a01 | 734 | lo.to(self.prev_token.span), |
dfeec247 XL |
735 | "remove the parentheses", |
736 | snippet, | |
737 | Applicability::MachineApplicable, | |
738 | ); | |
739 | } | |
740 | err.emit(); | |
741 | Ok(()) | |
742 | } | |
743 | ||
94222f64 | 744 | /// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `~const Trait`. |
dfeec247 XL |
745 | /// |
746 | /// If no modifiers are present, this does not consume any tokens. | |
747 | /// | |
748 | /// ``` | |
94222f64 | 749 | /// TY_BOUND_MODIFIERS = ["~const"] ["?"] |
dfeec247 | 750 | /// ``` |
94222f64 XL |
751 | fn parse_ty_bound_modifiers(&mut self) -> PResult<'a, BoundModifiers> { |
752 | let maybe_const = if self.eat(&token::Tilde) { | |
753 | let tilde = self.prev_token.span; | |
754 | self.expect_keyword(kw::Const)?; | |
755 | let span = tilde.to(self.prev_token.span); | |
756 | self.sess.gated_spans.gate(sym::const_trait_impl, span); | |
757 | Some(span) | |
758 | } else { | |
759 | None | |
760 | }; | |
dfeec247 | 761 | |
94222f64 | 762 | let maybe = if self.eat(&token::Question) { Some(self.prev_token.span) } else { None }; |
dfeec247 | 763 | |
94222f64 | 764 | Ok(BoundModifiers { maybe, maybe_const }) |
dfeec247 XL |
765 | } |
766 | ||
767 | /// Parses a type bound according to: | |
768 | /// ``` | |
769 | /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) | |
770 | /// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH | |
771 | /// ``` | |
772 | /// | |
94222f64 | 773 | /// For example, this grammar accepts `~const ?for<'a: 'b> m::Trait<'a>`. |
dfeec247 XL |
774 | fn parse_generic_ty_bound( |
775 | &mut self, | |
776 | lo: Span, | |
777 | has_parens: bool, | |
778 | modifiers: BoundModifiers, | |
779 | ) -> PResult<'a, GenericBound> { | |
780 | let lifetime_defs = self.parse_late_bound_lifetime_defs()?; | |
781 | let path = self.parse_path(PathStyle::Type)?; | |
782 | if has_parens { | |
17df50a5 XL |
783 | if self.token.is_like_plus() { |
784 | // Someone has written something like `&dyn (Trait + Other)`. The correct code | |
785 | // would be `&(dyn Trait + Other)`, but we don't have access to the appropriate | |
786 | // span to suggest that. When written as `&dyn Trait + Other`, an appropriate | |
787 | // suggestion is given. | |
788 | let bounds = vec![]; | |
789 | self.parse_remaining_bounds(bounds, true)?; | |
790 | self.expect(&token::CloseDelim(token::Paren))?; | |
791 | let sp = vec![lo, self.prev_token.span]; | |
792 | let sugg: Vec<_> = sp.iter().map(|sp| (*sp, String::new())).collect(); | |
793 | self.struct_span_err(sp, "incorrect braces around trait bounds") | |
794 | .multipart_suggestion( | |
795 | "remove the parentheses", | |
796 | sugg, | |
797 | Applicability::MachineApplicable, | |
798 | ) | |
799 | .emit(); | |
800 | } else { | |
801 | self.expect(&token::CloseDelim(token::Paren))?; | |
802 | } | |
416331ca XL |
803 | } |
804 | ||
dfeec247 | 805 | let modifier = modifiers.to_trait_bound_modifier(); |
74b04a01 | 806 | let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_token.span)); |
dfeec247 | 807 | Ok(GenericBound::Trait(poly_trait, modifier)) |
416331ca XL |
808 | } |
809 | ||
dfeec247 | 810 | /// Optionally parses `for<$generic_params>`. |
416331ca XL |
811 | pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> { |
812 | if self.eat_keyword(kw::For) { | |
813 | self.expect_lt()?; | |
814 | let params = self.parse_generic_params()?; | |
815 | self.expect_gt()?; | |
816 | // We rely on AST validation to rule out invalid cases: There must not be type | |
817 | // parameters, and the lifetime parameters must not have bounds. | |
818 | Ok(params) | |
819 | } else { | |
820 | Ok(Vec::new()) | |
821 | } | |
822 | } | |
823 | ||
3dfed10e | 824 | pub(super) fn check_lifetime(&mut self) -> bool { |
416331ca XL |
825 | self.expected_tokens.push(TokenType::Lifetime); |
826 | self.token.is_lifetime() | |
827 | } | |
828 | ||
829 | /// Parses a single lifetime `'a` or panics. | |
3dfed10e | 830 | pub(super) fn expect_lifetime(&mut self) -> Lifetime { |
416331ca | 831 | if let Some(ident) = self.token.lifetime() { |
416331ca | 832 | self.bump(); |
74b04a01 | 833 | Lifetime { ident, id: ast::DUMMY_NODE_ID } |
416331ca XL |
834 | } else { |
835 | self.span_bug(self.token.span, "not a lifetime") | |
836 | } | |
837 | } | |
e74abb32 XL |
838 | |
839 | pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> { | |
1b1a35ee | 840 | P(Ty { kind, span, id: ast::DUMMY_NODE_ID, tokens: None }) |
e74abb32 | 841 | } |
416331ca | 842 | } |