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