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.eat(&token::OpenDelim(token::Paren)) {
77 // `(TYPE)` is a parenthesized type.
78 // `(TYPE,)` is a tuple with a single field of type TYPE.
80 let mut last_comma = false;
81 while self.token != token::CloseDelim(token::Paren) {
82 ts.push(self.parse_ty()?);
83 if self.eat(&token::Comma) {
90 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
91 self.expect(&token::CloseDelim(token::Paren))?;
93 if ts.len() == 1 && !last_comma {
94 let ty = ts.into_iter().nth(0).unwrap().into_inner();
95 let maybe_bounds = allow_plus && self.token.is_like_plus();
97 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
98 TyKind::Path(None, ref path) if maybe_bounds => {
99 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
101 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
102 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
103 let path = match bounds[0] {
104 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
105 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
107 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
110 _ => TyKind::Paren(P(ty))
115 } else if self.eat(&token::Not) {
118 } else if self.eat(&token::BinOp(token::Star)) {
120 TyKind::Ptr(self.parse_ptr()?)
121 } else if self.eat(&token::OpenDelim(token::Bracket)) {
123 let t = self.parse_ty()?;
124 // Parse optional `; EXPR` in `[TYPE; EXPR]`
125 let t = match self.maybe_parse_fixed_length_of_vec()? {
126 None => TyKind::Slice(t),
127 Some(length) => TyKind::Array(t, AnonConst {
128 id: ast::DUMMY_NODE_ID,
132 self.expect(&token::CloseDelim(token::Bracket))?;
134 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
137 self.parse_borrowed_pointee()?
138 } else if self.eat_keyword_noexpect(kw::Typeof) {
140 // In order to not be ambiguous, the type must be surrounded by parens.
141 self.expect(&token::OpenDelim(token::Paren))?;
143 id: ast::DUMMY_NODE_ID,
144 value: self.parse_expr()?,
146 self.expect(&token::CloseDelim(token::Paren))?;
148 } else if self.eat_keyword(kw::Underscore) {
149 // A type to be inferred `_`
151 } else if self.token_is_bare_fn_keyword() {
152 // Function pointer type
153 self.parse_ty_bare_fn(Vec::new())?
154 } else if self.check_keyword(kw::For) {
155 // Function pointer type or bound list (trait object type) starting with a poly-trait.
156 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
157 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
158 let lo = self.token.span;
159 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
160 if self.token_is_bare_fn_keyword() {
161 self.parse_ty_bare_fn(lifetime_defs)?
163 let path = self.parse_path(PathStyle::Type)?;
164 let parse_plus = allow_plus && self.check_plus();
165 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
167 } else if self.eat_keyword(kw::Impl) {
168 // Always parse bounds greedily for better error recovery.
169 let bounds = self.parse_generic_bounds(None)?;
170 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
171 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
172 } else if self.check_keyword(kw::Dyn) &&
173 (self.token.span.rust_2018() ||
174 self.look_ahead(1, |t| t.can_begin_bound() &&
175 !can_continue_type_after_non_fn_ident(t))) {
176 self.bump(); // `dyn`
177 // Always parse bounds greedily for better error recovery.
178 let bounds = self.parse_generic_bounds(None)?;
179 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
180 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
181 } else if self.check(&token::Question) ||
182 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
183 // Bound list (trait object type)
184 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
185 TraitObjectSyntax::None)
186 } else if self.eat_lt() {
188 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
189 TyKind::Path(Some(qself), path)
190 } else if self.token.is_path_start() {
192 let path = self.parse_path(PathStyle::Type)?;
193 if self.eat(&token::Not) {
194 // Macro invocation in type position
195 let args = self.parse_mac_args()?;
199 prior_type_ascription: self.last_type_ascription,
203 // Just a type path or bound list (trait object type) starting with a trait.
205 // `Trait1 + Trait2 + 'a`
206 if allow_plus && self.check_plus() {
207 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
209 TyKind::Path(None, path)
212 } else if self.eat(&token::DotDotDot) {
213 if allow_c_variadic {
216 // FIXME(Centril): Should we just allow `...` syntactically
217 // anywhere in a type and use semantic restrictions instead?
219 self.sess.span_diagnostic,
220 lo.to(self.prev_span),
222 "C-variadic type `...` may not be nested inside another type",
229 let msg = format!("expected type, found {}", self.this_token_descr());
230 let mut err = self.fatal(&msg);
231 err.span_label(self.token.span, "expected type");
232 self.maybe_annotate_with_ascription(&mut err, true);
236 let span = lo.to(self.prev_span);
237 let ty = self.mk_ty(span, kind);
239 // Try to recover from use of `+` with incorrect priority.
240 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
241 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
242 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
245 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
246 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
247 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
248 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
250 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
251 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
253 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
256 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
257 let mutbl = self.parse_const_or_mut().unwrap_or_else(|| {
258 let span = self.prev_span;
259 let msg = "expected mut or const in raw pointer type";
260 self.struct_span_err(span, msg)
261 .span_label(span, msg)
262 .help("use `*mut T` or `*const T` as appropriate")
264 Mutability::Immutable
266 let t = self.parse_ty_no_plus()?;
267 Ok(MutTy { ty: t, mutbl })
270 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
271 if self.eat(&token::Semi) {
272 Ok(Some(self.parse_expr()?))
278 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
279 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
280 let mutbl = self.parse_mutability();
281 let ty = self.parse_ty_no_plus()?;
282 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty, mutbl }));
285 /// Is the current token one of the keywords that signals a bare function type?
286 fn token_is_bare_fn_keyword(&mut self) -> bool {
287 self.check_keyword(kw::Fn) ||
288 self.check_keyword(kw::Unsafe) ||
289 self.check_keyword(kw::Extern)
292 /// Parses a `TyKind::BareFn` type.
293 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
296 [unsafe] [extern "ABI"] fn (S) -> T
306 let unsafety = self.parse_unsafety();
307 let ext = self.parse_extern()?;
308 self.expect_keyword(kw::Fn)?;
310 is_self_allowed: false,
311 is_name_required: |_| false,
313 let decl = self.parse_fn_decl(cfg, false)?;
314 Ok(TyKind::BareFn(P(BareFnTy {
322 pub(super) fn parse_generic_bounds(&mut self,
323 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
324 self.parse_generic_bounds_common(true, colon_span)
327 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
330 /// BOUND = TY_BOUND | LT_BOUND
331 /// LT_BOUND = LIFETIME (e.g., `'a`)
332 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
333 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
335 fn parse_generic_bounds_common(&mut self,
337 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
338 let mut bounds = Vec::new();
339 let mut negative_bounds = Vec::new();
340 let mut last_plus_span = None;
341 let mut was_negative = false;
343 // This needs to be synchronized with `TokenKind::can_begin_bound`.
344 let is_bound_start = self.check_path() || self.check_lifetime() ||
345 self.check(&token::Not) || // used for error reporting only
346 self.check(&token::Question) ||
347 self.check_keyword(kw::For) ||
348 self.check(&token::OpenDelim(token::Paren));
350 let lo = self.token.span;
351 let has_parens = self.eat(&token::OpenDelim(token::Paren));
352 let inner_lo = self.token.span;
353 let is_negative = self.eat(&token::Not);
354 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
355 if self.token.is_lifetime() {
356 if let Some(question_span) = question {
357 self.span_err(question_span,
358 "`?` may only modify trait bounds, not lifetime bounds");
360 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
362 let inner_span = inner_lo.to(self.prev_span);
363 self.expect(&token::CloseDelim(token::Paren))?;
364 let mut err = self.struct_span_err(
365 lo.to(self.prev_span),
366 "parenthesized lifetime bounds are not supported"
368 if let Ok(snippet) = self.span_to_snippet(inner_span) {
369 err.span_suggestion_short(
370 lo.to(self.prev_span),
371 "remove the parentheses",
373 Applicability::MachineApplicable
379 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
380 let path = self.parse_path(PathStyle::Type)?;
382 self.expect(&token::CloseDelim(token::Paren))?;
384 let poly_span = lo.to(self.prev_span);
387 if let Some(sp) = last_plus_span.or(colon_span) {
388 negative_bounds.push(sp.to(poly_span));
391 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
392 let modifier = if question.is_some() {
393 TraitBoundModifier::Maybe
395 TraitBoundModifier::None
397 bounds.push(GenericBound::Trait(poly_trait, modifier));
404 if !allow_plus || !self.eat_plus() {
407 last_plus_span = Some(self.prev_span);
411 if !negative_bounds.is_empty() || was_negative {
412 let negative_bounds_len = negative_bounds.len();
413 let last_span = negative_bounds.last().map(|sp| *sp);
414 let mut err = self.struct_span_err(
416 "negative trait bounds are not supported",
418 if let Some(sp) = last_span {
419 err.span_label(sp, "negative trait bounds are not supported");
421 if let Some(bound_list) = colon_span {
422 let bound_list = bound_list.to(self.prev_span);
423 let mut new_bound_list = String::new();
424 if !bounds.is_empty() {
425 let mut snippets = bounds.iter().map(|bound| bound.span())
426 .map(|span| self.span_to_snippet(span));
427 while let Some(Ok(snippet)) = snippets.next() {
428 new_bound_list.push_str(" + ");
429 new_bound_list.push_str(&snippet);
431 new_bound_list = new_bound_list.replacen(" +", ":", 1);
433 err.span_suggestion_hidden(
435 &format!("remove the trait bound{}", pluralize!(negative_bounds_len)),
437 Applicability::MachineApplicable,
446 pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
447 if self.eat_keyword(kw::For) {
449 let params = self.parse_generic_params()?;
451 // We rely on AST validation to rule out invalid cases: There must not be type
452 // parameters, and the lifetime parameters must not have bounds.
459 pub fn check_lifetime(&mut self) -> bool {
460 self.expected_tokens.push(TokenType::Lifetime);
461 self.token.is_lifetime()
464 /// Parses a single lifetime `'a` or panics.
465 pub fn expect_lifetime(&mut self) -> Lifetime {
466 if let Some(ident) = self.token.lifetime() {
467 let span = self.token.span;
469 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
471 self.span_bug(self.token.span, "not a lifetime")
475 pub(super) fn mk_ty(&self, span: Span, kind: TyKind) -> P<Ty> {
476 P(Ty { kind, span, id: ast::DUMMY_NODE_ID })