1 use super::{Parser, PathStyle, PrevTokenKind, TokenType};
2 use super::item::ParamCfg;
4 use crate::{maybe_whole, maybe_recover_from_interpolated_ty_qpath};
6 use rustc_errors::{PResult, Applicability, pluralize};
7 use rustc_error_codes::*;
9 use syntax::ast::{self, Ty, TyKind, MutTy, BareFnTy, FunctionRetTy, GenericParam, Lifetime, Ident};
10 use syntax::ast::{TraitBoundModifier, TraitObjectSyntax, GenericBound, GenericBounds, PolyTraitRef};
11 use syntax::ast::{Mutability, Mac};
12 use syntax::token::{self, Token};
13 use syntax::struct_span_err;
14 use syntax_pos::source_map::Span;
15 use syntax_pos::symbol::kw;
17 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
18 /// `IDENT<<u8 as Trait>::AssocTy>`.
20 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
21 /// that `IDENT` is not the ident of a fn trait.
22 fn can_continue_type_after_non_fn_ident(t: &Token) -> bool {
23 t == &token::ModSep || t == &token::Lt ||
24 t == &token::BinOp(token::Shl)
29 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
30 self.parse_ty_common(true, true, false)
33 /// Parse a type suitable for a function or function pointer parameter.
34 /// The difference from `parse_ty` is that this version allows `...`
35 /// (`CVarArgs`) at the top level of the the type.
36 pub(super) fn parse_ty_for_param(&mut self) -> PResult<'a, P<Ty>> {
37 self.parse_ty_common(true, true, true)
40 /// Parses a type in restricted contexts where `+` is not permitted.
42 /// Example 1: `&'a TYPE`
43 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
44 /// Example 2: `value1 as TYPE + value2`
45 /// `+` is prohibited to avoid interactions with expression grammar.
46 pub(super) fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
47 self.parse_ty_common(false, true, false)
50 /// Parses an optional return type `[ -> TY ]` in a function declaration.
51 pub(super) fn parse_ret_ty(
54 allow_qpath_recovery: bool,
55 ) -> PResult<'a, FunctionRetTy> {
56 Ok(if self.eat(&token::RArrow) {
57 // FIXME(Centril): Can we unconditionally `allow_plus`?
58 FunctionRetTy::Ty(self.parse_ty_common(allow_plus, allow_qpath_recovery, false)?)
60 FunctionRetTy::Default(self.token.span.shrink_to_lo())
67 allow_qpath_recovery: bool,
68 // Is `...` (`CVarArgs`) legal in the immediate top level call?
69 allow_c_variadic: bool,
70 ) -> PResult<'a, P<Ty>> {
71 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
72 maybe_whole!(self, NtTy, |x| x);
74 let lo = self.token.span;
75 let mut impl_dyn_multi = false;
76 let kind = if self.check(&token::OpenDelim(token::Paren)) {
77 self.parse_ty_tuple_or_parens(lo, allow_plus)?
78 } else if self.eat(&token::Not) {
81 } else if self.eat(&token::BinOp(token::Star)) {
83 } else if self.eat(&token::OpenDelim(token::Bracket)) {
84 self.parse_array_or_slice_ty()?
85 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
88 self.parse_borrowed_pointee()?
89 } else if self.eat_keyword_noexpect(kw::Typeof) {
90 self.parse_typeof_ty()?
91 } else if self.eat_keyword(kw::Underscore) {
92 // A type to be inferred `_`
94 } else if self.token_is_bare_fn_keyword() {
95 // Function pointer type
96 self.parse_ty_bare_fn(Vec::new())?
97 } else if self.check_keyword(kw::For) {
98 // Function pointer type or bound list (trait object type) starting with a poly-trait.
99 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
100 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
101 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
102 if self.token_is_bare_fn_keyword() {
103 self.parse_ty_bare_fn(lifetime_defs)?
105 let path = self.parse_path(PathStyle::Type)?;
106 let parse_plus = allow_plus && self.check_plus();
107 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
109 } else if self.eat_keyword(kw::Impl) {
110 self.parse_impl_ty(&mut impl_dyn_multi)?
111 } else if self.is_explicit_dyn_type() {
112 self.parse_dyn_ty(&mut impl_dyn_multi)?
113 } else if self.check(&token::Question)
114 || self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus())
116 // Bound list (trait object type)
117 let bounds = self.parse_generic_bounds_common(allow_plus, None)?;
118 TyKind::TraitObject(bounds, TraitObjectSyntax::None)
119 } else if self.eat_lt() {
121 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
122 TyKind::Path(Some(qself), path)
123 } else if self.token.is_path_start() {
125 let path = self.parse_path(PathStyle::Type)?;
126 if self.eat(&token::Not) {
127 // Macro invocation in type position
128 let args = self.parse_mac_args()?;
132 prior_type_ascription: self.last_type_ascription,
136 // Just a type path or bound list (trait object type) starting with a trait.
138 // `Trait1 + Trait2 + 'a`
139 if allow_plus && self.check_plus() {
140 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
142 TyKind::Path(None, path)
145 } else if self.eat(&token::DotDotDot) {
146 if allow_c_variadic {
149 // FIXME(Centril): Should we just allow `...` syntactically
150 // anywhere in a type and use semantic restrictions instead?
152 self.sess.span_diagnostic,
153 lo.to(self.prev_span),
155 "C-variadic type `...` may not be nested inside another type",
162 let msg = format!("expected type, found {}", self.this_token_descr());
163 let mut err = self.fatal(&msg);
164 err.span_label(self.token.span, "expected type");
165 self.maybe_annotate_with_ascription(&mut err, true);
169 let span = lo.to(self.prev_span);
170 let ty = self.mk_ty(span, kind);
172 // Try to recover from use of `+` with incorrect priority.
173 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
174 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
175 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
179 /// - `(TYPE)`, a parenthesized type.
180 /// - `(TYPE,)`, a tuple with a single field of type TYPE.
181 fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: bool) -> PResult<'a, TyKind> {
182 let mut trailing_plus = false;
183 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
184 let ty = p.parse_ty()?;
185 trailing_plus = p.prev_token_kind == PrevTokenKind::Plus;
189 if ts.len() == 1 && !trailing {
190 let ty = ts.into_iter().nth(0).unwrap().into_inner();
191 let maybe_bounds = allow_plus && self.token.is_like_plus();
193 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
194 TyKind::Path(None, path) if maybe_bounds => {
195 self.parse_remaining_bounds(Vec::new(), path, lo, true)
197 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
198 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
199 let path = match bounds.remove(0) {
200 GenericBound::Trait(pt, ..) => pt.trait_ref.path,
201 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
203 self.parse_remaining_bounds(Vec::new(), path, lo, true)
206 _ => Ok(TyKind::Paren(P(ty)))
213 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
214 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
215 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
216 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
218 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
219 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
221 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
224 /// Parses a raw pointer type: `*[const | mut] $type`.
225 fn parse_ty_ptr(&mut self) -> PResult<'a, TyKind> {
226 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
227 let span = self.prev_span;
228 let msg = "expected mut or const in raw pointer type";
229 self.struct_span_err(span, msg)
230 .span_label(span, msg)
231 .help("use `*mut T` or `*const T` as appropriate")
233 Mutability::Immutable
235 let ty = self.parse_ty_no_plus()?;
236 Ok(TyKind::Ptr(MutTy { ty, mutbl }))
239 /// Parses an array (`[TYPE; EXPR]`) or slice (`[TYPE]`) type.
240 /// The opening `[` bracket is already eaten.
241 fn parse_array_or_slice_ty(&mut self) -> PResult<'a, TyKind> {
242 let elt_ty = self.parse_ty()?;
243 let ty = if self.eat(&token::Semi) {
244 TyKind::Array(elt_ty, self.parse_anon_const_expr()?)
246 TyKind::Slice(elt_ty)
248 self.expect(&token::CloseDelim(token::Bracket))?;
252 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
253 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
254 let mutbl = self.parse_mutability();
255 let ty = self.parse_ty_no_plus()?;
256 Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }))
259 // Parses the `typeof(EXPR)`.
260 // To avoid ambiguity, the type is surrounded by parenthesis.
261 fn parse_typeof_ty(&mut self) -> PResult<'a, TyKind> {
262 self.expect(&token::OpenDelim(token::Paren))?;
263 let expr = self.parse_anon_const_expr()?;
264 self.expect(&token::CloseDelim(token::Paren))?;
265 Ok(TyKind::Typeof(expr))
268 /// Is the current token one of the keywords that signals a bare function type?
269 fn token_is_bare_fn_keyword(&mut self) -> bool {
270 self.check_keyword(kw::Fn) ||
271 self.check_keyword(kw::Unsafe) ||
272 self.check_keyword(kw::Extern)
275 /// Parses a `TyKind::BareFn` type.
276 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
279 [unsafe] [extern "ABI"] fn (S) -> T
289 let unsafety = self.parse_unsafety();
290 let ext = self.parse_extern()?;
291 self.expect_keyword(kw::Fn)?;
293 is_self_allowed: false,
294 is_name_required: |_| false,
296 let decl = self.parse_fn_decl(cfg, false)?;
297 Ok(TyKind::BareFn(P(BareFnTy {
305 /// Parses an `impl B0 + ... + Bn` type.
306 fn parse_impl_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
307 // Always parse bounds greedily for better error recovery.
308 let bounds = self.parse_generic_bounds(None)?;
309 *impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
310 Ok(TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds))
313 /// Is a `dyn B0 + ... + Bn` type allowed here?
314 fn is_explicit_dyn_type(&mut self) -> bool {
315 self.check_keyword(kw::Dyn)
316 && (self.token.span.rust_2018()
317 || self.look_ahead(1, |t| {
318 t.can_begin_bound() && !can_continue_type_after_non_fn_ident(t)
322 /// Parses a `dyn B0 + ... + Bn` type.
324 /// Note that this does *not* parse bare trait objects.
325 fn parse_dyn_ty(&mut self, impl_dyn_multi: &mut bool) -> PResult<'a, TyKind> {
326 self.bump(); // `dyn`
327 // Always parse bounds greedily for better error recovery.
328 let bounds = self.parse_generic_bounds(None)?;
329 *impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
330 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn))
333 pub(super) fn parse_generic_bounds(&mut self,
334 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
335 self.parse_generic_bounds_common(true, colon_span)
338 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
341 /// BOUND = TY_BOUND | LT_BOUND
342 /// LT_BOUND = LIFETIME (e.g., `'a`)
343 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
344 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
346 fn parse_generic_bounds_common(&mut self,
348 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
349 let mut bounds = Vec::new();
350 let mut negative_bounds = Vec::new();
351 let mut last_plus_span = None;
352 let mut was_negative = false;
354 // This needs to be synchronized with `TokenKind::can_begin_bound`.
355 let is_bound_start = self.check_path() || self.check_lifetime() ||
356 self.check(&token::Not) || // used for error reporting only
357 self.check(&token::Question) ||
358 self.check_keyword(kw::For) ||
359 self.check(&token::OpenDelim(token::Paren));
361 let lo = self.token.span;
362 let has_parens = self.eat(&token::OpenDelim(token::Paren));
363 let inner_lo = self.token.span;
364 let is_negative = self.eat(&token::Not);
365 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
366 if self.token.is_lifetime() {
367 if let Some(question_span) = question {
368 self.span_err(question_span,
369 "`?` may only modify trait bounds, not lifetime bounds");
371 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
373 let inner_span = inner_lo.to(self.prev_span);
374 self.expect(&token::CloseDelim(token::Paren))?;
375 let mut err = self.struct_span_err(
376 lo.to(self.prev_span),
377 "parenthesized lifetime bounds are not supported"
379 if let Ok(snippet) = self.span_to_snippet(inner_span) {
380 err.span_suggestion_short(
381 lo.to(self.prev_span),
382 "remove the parentheses",
384 Applicability::MachineApplicable
390 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
391 let path = self.parse_path(PathStyle::Type)?;
393 self.expect(&token::CloseDelim(token::Paren))?;
395 let poly_span = lo.to(self.prev_span);
398 if let Some(sp) = last_plus_span.or(colon_span) {
399 negative_bounds.push(sp.to(poly_span));
402 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
403 let modifier = if question.is_some() {
404 TraitBoundModifier::Maybe
406 TraitBoundModifier::None
408 bounds.push(GenericBound::Trait(poly_trait, modifier));
415 if !allow_plus || !self.eat_plus() {
418 last_plus_span = Some(self.prev_span);
422 if !negative_bounds.is_empty() || was_negative {
423 let negative_bounds_len = negative_bounds.len();
424 let last_span = negative_bounds.last().map(|sp| *sp);
425 let mut err = self.struct_span_err(
427 "negative trait bounds are not supported",
429 if let Some(sp) = last_span {
430 err.span_label(sp, "negative trait bounds are not supported");
432 if let Some(bound_list) = colon_span {
433 let bound_list = bound_list.to(self.prev_span);
434 let mut new_bound_list = String::new();
435 if !bounds.is_empty() {
436 let mut snippets = bounds.iter().map(|bound| bound.span())
437 .map(|span| self.span_to_snippet(span));
438 while let Some(Ok(snippet)) = snippets.next() {
439 new_bound_list.push_str(" + ");
440 new_bound_list.push_str(&snippet);
442 new_bound_list = new_bound_list.replacen(" +", ":", 1);
444 err.span_suggestion_hidden(
446 &format!("remove the trait bound{}", pluralize!(negative_bounds_len)),
448 Applicability::MachineApplicable,
457 pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
458 if self.eat_keyword(kw::For) {
460 let params = self.parse_generic_params()?;
462 // We rely on AST validation to rule out invalid cases: There must not be type
463 // parameters, and the lifetime parameters must not have bounds.
470 pub fn check_lifetime(&mut self) -> bool {
471 self.expected_tokens.push(TokenType::Lifetime);
472 self.token.is_lifetime()
475 /// Parses a single lifetime `'a` or panics.
476 pub fn expect_lifetime(&mut self) -> Lifetime {
477 if let Some(ident) = self.token.lifetime() {
478 let span = self.token.span;
480 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
482 self.span_bug(self.token.span, "not a lifetime")
486 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
487 P(Ty { kind, span, id: ast::DUMMY_NODE_ID })