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