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, AnonConst, 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 TyKind::Ptr(self.parse_ptr()?)
84 } else if self.eat(&token::OpenDelim(token::Bracket)) {
86 let t = self.parse_ty()?;
87 // Parse optional `; EXPR` in `[TYPE; EXPR]`
88 let t = match self.maybe_parse_fixed_length_of_vec()? {
89 None => TyKind::Slice(t),
90 Some(length) => TyKind::Array(t, AnonConst {
91 id: ast::DUMMY_NODE_ID,
95 self.expect(&token::CloseDelim(token::Bracket))?;
97 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
100 self.parse_borrowed_pointee()?
101 } else if self.eat_keyword_noexpect(kw::Typeof) {
103 // In order to not be ambiguous, the type must be surrounded by parens.
104 self.expect(&token::OpenDelim(token::Paren))?;
106 id: ast::DUMMY_NODE_ID,
107 value: self.parse_expr()?,
109 self.expect(&token::CloseDelim(token::Paren))?;
111 } else if self.eat_keyword(kw::Underscore) {
112 // A type to be inferred `_`
114 } else if self.token_is_bare_fn_keyword() {
115 // Function pointer type
116 self.parse_ty_bare_fn(Vec::new())?
117 } else if self.check_keyword(kw::For) {
118 // Function pointer type or bound list (trait object type) starting with a poly-trait.
119 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
120 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
121 let lo = self.token.span;
122 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
123 if self.token_is_bare_fn_keyword() {
124 self.parse_ty_bare_fn(lifetime_defs)?
126 let path = self.parse_path(PathStyle::Type)?;
127 let parse_plus = allow_plus && self.check_plus();
128 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
130 } else if self.eat_keyword(kw::Impl) {
131 // Always parse bounds greedily for better error recovery.
132 let bounds = self.parse_generic_bounds(None)?;
133 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
134 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
135 } else if self.check_keyword(kw::Dyn) &&
136 (self.token.span.rust_2018() ||
137 self.look_ahead(1, |t| t.can_begin_bound() &&
138 !can_continue_type_after_non_fn_ident(t))) {
139 self.bump(); // `dyn`
140 // Always parse bounds greedily for better error recovery.
141 let bounds = self.parse_generic_bounds(None)?;
142 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
143 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
144 } else if self.check(&token::Question) ||
145 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
146 // Bound list (trait object type)
147 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
148 TraitObjectSyntax::None)
149 } else if self.eat_lt() {
151 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
152 TyKind::Path(Some(qself), path)
153 } else if self.token.is_path_start() {
155 let path = self.parse_path(PathStyle::Type)?;
156 if self.eat(&token::Not) {
157 // Macro invocation in type position
158 let args = self.parse_mac_args()?;
162 prior_type_ascription: self.last_type_ascription,
166 // Just a type path or bound list (trait object type) starting with a trait.
168 // `Trait1 + Trait2 + 'a`
169 if allow_plus && self.check_plus() {
170 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
172 TyKind::Path(None, path)
175 } else if self.eat(&token::DotDotDot) {
176 if allow_c_variadic {
179 // FIXME(Centril): Should we just allow `...` syntactically
180 // anywhere in a type and use semantic restrictions instead?
182 self.sess.span_diagnostic,
183 lo.to(self.prev_span),
185 "C-variadic type `...` may not be nested inside another type",
192 let msg = format!("expected type, found {}", self.this_token_descr());
193 let mut err = self.fatal(&msg);
194 err.span_label(self.token.span, "expected type");
195 self.maybe_annotate_with_ascription(&mut err, true);
199 let span = lo.to(self.prev_span);
200 let ty = self.mk_ty(span, kind);
202 // Try to recover from use of `+` with incorrect priority.
203 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
204 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
205 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
209 /// - `(TYPE)`, a parenthesized type.
210 /// - `(TYPE,)`, a tuple with a single field of type TYPE.
211 fn parse_ty_tuple_or_parens(&mut self, lo: Span, allow_plus: bool) -> PResult<'a, TyKind> {
212 let mut trailing_plus = false;
213 let (ts, trailing) = self.parse_paren_comma_seq(|p| {
214 let ty = p.parse_ty()?;
215 trailing_plus = p.prev_token_kind == PrevTokenKind::Plus;
219 if ts.len() == 1 && !trailing {
220 let ty = ts.into_iter().nth(0).unwrap().into_inner();
221 let maybe_bounds = allow_plus && self.token.is_like_plus();
223 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
224 TyKind::Path(None, path) if maybe_bounds => {
225 self.parse_remaining_bounds(Vec::new(), path, lo, true)
227 TyKind::TraitObject(mut bounds, TraitObjectSyntax::None)
228 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
229 let path = match bounds.remove(0) {
230 GenericBound::Trait(pt, ..) => pt.trait_ref.path,
231 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
233 self.parse_remaining_bounds(Vec::new(), path, lo, true)
236 _ => Ok(TyKind::Paren(P(ty)))
243 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
244 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
245 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
246 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
248 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
249 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
251 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
254 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
255 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
256 let span = self.prev_span;
257 let msg = "expected mut or const in raw pointer type";
258 self.struct_span_err(span, msg)
259 .span_label(span, msg)
260 .help("use `*mut T` or `*const T` as appropriate")
262 Mutability::Immutable
264 let t = self.parse_ty_no_plus()?;
265 Ok(MutTy { ty: t, mutbl })
268 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
269 if self.eat(&token::Semi) {
270 Ok(Some(self.parse_expr()?))
276 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
277 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
278 let mutbl = self.parse_mutability();
279 let ty = self.parse_ty_no_plus()?;
280 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }));
283 /// Is the current token one of the keywords that signals a bare function type?
284 fn token_is_bare_fn_keyword(&mut self) -> bool {
285 self.check_keyword(kw::Fn) ||
286 self.check_keyword(kw::Unsafe) ||
287 self.check_keyword(kw::Extern)
290 /// Parses a `TyKind::BareFn` type.
291 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
294 [unsafe] [extern "ABI"] fn (S) -> T
304 let unsafety = self.parse_unsafety();
305 let ext = self.parse_extern()?;
306 self.expect_keyword(kw::Fn)?;
308 is_self_allowed: false,
309 is_name_required: |_| false,
311 let decl = self.parse_fn_decl(cfg, false)?;
312 Ok(TyKind::BareFn(P(BareFnTy {
320 pub(super) fn parse_generic_bounds(&mut self,
321 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
322 self.parse_generic_bounds_common(true, colon_span)
325 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
328 /// BOUND = TY_BOUND | LT_BOUND
329 /// LT_BOUND = LIFETIME (e.g., `'a`)
330 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
331 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
333 fn parse_generic_bounds_common(&mut self,
335 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
336 let mut bounds = Vec::new();
337 let mut negative_bounds = Vec::new();
338 let mut last_plus_span = None;
339 let mut was_negative = false;
341 // This needs to be synchronized with `TokenKind::can_begin_bound`.
342 let is_bound_start = self.check_path() || self.check_lifetime() ||
343 self.check(&token::Not) || // used for error reporting only
344 self.check(&token::Question) ||
345 self.check_keyword(kw::For) ||
346 self.check(&token::OpenDelim(token::Paren));
348 let lo = self.token.span;
349 let has_parens = self.eat(&token::OpenDelim(token::Paren));
350 let inner_lo = self.token.span;
351 let is_negative = self.eat(&token::Not);
352 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
353 if self.token.is_lifetime() {
354 if let Some(question_span) = question {
355 self.span_err(question_span,
356 "`?` may only modify trait bounds, not lifetime bounds");
358 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
360 let inner_span = inner_lo.to(self.prev_span);
361 self.expect(&token::CloseDelim(token::Paren))?;
362 let mut err = self.struct_span_err(
363 lo.to(self.prev_span),
364 "parenthesized lifetime bounds are not supported"
366 if let Ok(snippet) = self.span_to_snippet(inner_span) {
367 err.span_suggestion_short(
368 lo.to(self.prev_span),
369 "remove the parentheses",
371 Applicability::MachineApplicable
377 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
378 let path = self.parse_path(PathStyle::Type)?;
380 self.expect(&token::CloseDelim(token::Paren))?;
382 let poly_span = lo.to(self.prev_span);
385 if let Some(sp) = last_plus_span.or(colon_span) {
386 negative_bounds.push(sp.to(poly_span));
389 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
390 let modifier = if question.is_some() {
391 TraitBoundModifier::Maybe
393 TraitBoundModifier::None
395 bounds.push(GenericBound::Trait(poly_trait, modifier));
402 if !allow_plus || !self.eat_plus() {
405 last_plus_span = Some(self.prev_span);
409 if !negative_bounds.is_empty() || was_negative {
410 let negative_bounds_len = negative_bounds.len();
411 let last_span = negative_bounds.last().map(|sp| *sp);
412 let mut err = self.struct_span_err(
414 "negative trait bounds are not supported",
416 if let Some(sp) = last_span {
417 err.span_label(sp, "negative trait bounds are not supported");
419 if let Some(bound_list) = colon_span {
420 let bound_list = bound_list.to(self.prev_span);
421 let mut new_bound_list = String::new();
422 if !bounds.is_empty() {
423 let mut snippets = bounds.iter().map(|bound| bound.span())
424 .map(|span| self.span_to_snippet(span));
425 while let Some(Ok(snippet)) = snippets.next() {
426 new_bound_list.push_str(" + ");
427 new_bound_list.push_str(&snippet);
429 new_bound_list = new_bound_list.replacen(" +", ":", 1);
431 err.span_suggestion_hidden(
433 &format!("remove the trait bound{}", pluralize!(negative_bounds_len)),
435 Applicability::MachineApplicable,
444 pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
445 if self.eat_keyword(kw::For) {
447 let params = self.parse_generic_params()?;
449 // We rely on AST validation to rule out invalid cases: There must not be type
450 // parameters, and the lifetime parameters must not have bounds.
457 pub fn check_lifetime(&mut self) -> bool {
458 self.expected_tokens.push(TokenType::Lifetime);
459 self.token.is_lifetime()
462 /// Parses a single lifetime `'a` or panics.
463 pub fn expect_lifetime(&mut self) -> Lifetime {
464 if let Some(ident) = self.token.lifetime() {
465 let span = self.token.span;
467 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
469 self.span_bug(self.token.span, "not a lifetime")
473 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
474 P(Ty { kind, span, id: ast::DUMMY_NODE_ID })