2 MultipleWhereClauses, UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody,
3 WhereClauseBeforeTupleStructBodySugg,
6 use super::{ForceCollect, Parser, TrailingToken};
8 use ast::token::Delimiter;
11 self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause,
13 use rustc_errors::{Applicability, PResult};
14 use rustc_span::symbol::{kw, Ident};
17 enum PredicateOrStructBody {
18 Predicate(ast::WherePredicate),
19 StructBody(Vec<ast::FieldDef>),
23 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
26 /// BOUND = LT_BOUND (e.g., `'a`)
28 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
29 let mut lifetimes = Vec::new();
30 while self.check_lifetime() {
31 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
40 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
41 fn parse_ty_param(&mut self, preceding_attrs: AttrVec) -> PResult<'a, GenericParam> {
42 let ident = self.parse_ident()?;
44 // Parse optional colon and param bounds.
45 let mut colon_span = None;
46 let bounds = if self.eat(&token::Colon) {
47 colon_span = Some(self.prev_token.span);
48 // recover from `impl Trait` in type param bound
49 if self.token.is_keyword(kw::Impl) {
50 let impl_span = self.token.span;
51 let snapshot = self.create_snapshot_for_diagnostic();
52 match self.parse_ty() {
54 if let TyKind::ImplTrait(_, bounds) = &(*p).kind {
55 let span = impl_span.to(self.token.span.shrink_to_lo());
56 let mut err = self.struct_span_err(
58 "expected trait bound, found `impl Trait` type",
60 err.span_label(span, "not a trait");
61 if let [bound, ..] = &bounds[..] {
62 err.span_suggestion_verbose(
63 impl_span.until(bound.span()),
64 "use the trait bounds directly",
66 Applicability::MachineApplicable,
77 self.restore_snapshot(snapshot);
79 self.parse_generic_bounds(colon_span)?
84 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
87 id: ast::DUMMY_NODE_ID,
88 attrs: preceding_attrs,
90 kind: GenericParamKind::Type { default },
91 is_placeholder: false,
96 pub(crate) fn parse_const_param(
98 preceding_attrs: AttrVec,
99 ) -> PResult<'a, GenericParam> {
100 let const_span = self.token.span;
102 self.expect_keyword(kw::Const)?;
103 let ident = self.parse_ident()?;
104 self.expect(&token::Colon)?;
105 let ty = self.parse_ty()?;
107 // Parse optional const generics default value.
108 let default = if self.eat(&token::Eq) { Some(self.parse_const_arg()?) } else { None };
112 id: ast::DUMMY_NODE_ID,
113 attrs: preceding_attrs,
115 kind: GenericParamKind::Const { ty, kw_span: const_span, default },
116 is_placeholder: false,
121 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
122 /// a trailing comma and erroneous trailing attributes.
123 pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
124 let mut params = Vec::new();
125 let mut done = false;
127 let attrs = self.parse_outer_attributes()?;
129 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
130 if this.eat_keyword_noexpect(kw::SelfUpper) {
131 // `Self` as a generic param is invalid. Here we emit the diagnostic and continue parsing
132 // as if `Self` never existed.
133 this.sess.emit_err(UnexpectedSelfInGenericParameters {
134 span: this.prev_token.span,
137 this.eat(&token::Comma);
140 let param = if this.check_lifetime() {
141 let lifetime = this.expect_lifetime();
142 // Parse lifetime parameter.
143 let (colon_span, bounds) = if this.eat(&token::Colon) {
144 (Some(this.prev_token.span), this.parse_lt_param_bounds())
148 Some(ast::GenericParam {
149 ident: lifetime.ident,
153 kind: ast::GenericParamKind::Lifetime,
154 is_placeholder: false,
157 } else if this.check_keyword(kw::Const) {
158 // Parse const parameter.
159 Some(this.parse_const_param(attrs)?)
160 } else if this.check_ident() {
161 // Parse type parameter.
162 Some(this.parse_ty_param(attrs)?)
163 } else if this.token.can_begin_type() {
164 // Trying to write an associated type bound? (#26271)
165 let snapshot = this.create_snapshot_for_diagnostic();
166 match this.parse_ty_where_predicate() {
167 Ok(where_predicate) => {
168 this.struct_span_err(
169 where_predicate.span(),
170 "bounds on associated types do not belong here",
172 .span_label(where_predicate.span(), "belongs in `where` clause")
174 // FIXME - try to continue parsing other generics?
175 return Ok((None, TrailingToken::None));
179 // FIXME - maybe we should overwrite 'self' outside of `collect_tokens`?
180 this.restore_snapshot(snapshot);
181 return Ok((None, TrailingToken::None));
185 // Check for trailing attributes and stop parsing.
186 if !attrs.is_empty() {
187 if !params.is_empty() {
188 this.struct_span_err(
190 "trailing attribute after generic parameter",
192 .span_label(attrs[0].span, "attributes must go before parameters")
195 this.struct_span_err(
197 "attribute without generic parameters",
201 "attributes are only permitted when preceding parameters",
206 return Ok((None, TrailingToken::None));
209 if !this.eat(&token::Comma) {
212 // We just ate the comma, so no need to use `TrailingToken`
213 Ok((param, TrailingToken::None))
216 if let Some(param) = param {
225 /// Parses a set of optional generic type parameter declarations. Where
226 /// clauses are not parsed here, and must be added later via
227 /// `parse_where_clause()`.
229 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
230 /// | ( < lifetimes , typaramseq ( , )? > )
231 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
232 pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
233 let span_lo = self.token.span;
234 let (params, span) = if self.eat_lt() {
235 let params = self.parse_generic_params()?;
237 (params, span_lo.to(self.prev_token.span))
239 (vec![], self.prev_token.span.shrink_to_hi())
243 where_clause: WhereClause {
244 has_where_token: false,
245 predicates: Vec::new(),
246 span: self.prev_token.span.shrink_to_hi(),
252 /// Parses an optional where-clause.
254 /// ```ignore (only-for-syntax-highlight)
255 /// where T : Trait<U, V> + 'b, 'a : 'b
257 pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
258 self.parse_where_clause_common(None).map(|(clause, _)| clause)
261 pub(super) fn parse_struct_where_clause(
264 body_insertion_point: Span,
265 ) -> PResult<'a, (WhereClause, Option<Vec<ast::FieldDef>>)> {
266 self.parse_where_clause_common(Some((struct_name, body_insertion_point)))
269 fn parse_where_clause_common(
271 struct_: Option<(Ident, Span)>,
272 ) -> PResult<'a, (WhereClause, Option<Vec<ast::FieldDef>>)> {
273 let mut where_clause = WhereClause {
274 has_where_token: false,
275 predicates: Vec::new(),
276 span: self.prev_token.span.shrink_to_hi(),
278 let mut tuple_struct_body = None;
280 if !self.eat_keyword(kw::Where) {
281 return Ok((where_clause, None));
283 where_clause.has_where_token = true;
284 let where_lo = self.prev_token.span;
286 // We are considering adding generics to the `where` keyword as an alternative higher-rank
287 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
288 // change we parse those generics now, but report an error.
289 if self.choose_generics_over_qpath(0) {
290 let generics = self.parse_generics()?;
291 self.struct_span_err(
293 "generic parameters on `where` clauses are reserved for future use",
295 .span_label(generics.span, "currently unsupported")
300 let where_sp = where_lo.to(self.prev_token.span);
301 let pred_lo = self.token.span;
302 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
303 let lifetime = self.expect_lifetime();
304 // Bounds starting with a colon are mandatory, but possibly empty.
305 self.expect(&token::Colon)?;
306 let bounds = self.parse_lt_param_bounds();
307 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
308 ast::WhereRegionPredicate {
309 span: pred_lo.to(self.prev_token.span),
314 } else if self.check_type() {
315 match self.parse_ty_where_predicate_or_recover_tuple_struct_body(
316 struct_, pred_lo, where_sp,
318 PredicateOrStructBody::Predicate(pred) => where_clause.predicates.push(pred),
319 PredicateOrStructBody::StructBody(body) => {
320 tuple_struct_body = Some(body);
328 let prev_token = self.prev_token.span;
329 let ate_comma = self.eat(&token::Comma);
331 if self.eat_keyword_noexpect(kw::Where) {
332 self.sess.emit_err(MultipleWhereClauses {
333 span: self.token.span,
335 between: prev_token.shrink_to_hi().to(self.prev_token.span),
337 } else if !ate_comma {
342 where_clause.span = where_lo.to(self.prev_token.span);
343 Ok((where_clause, tuple_struct_body))
346 fn parse_ty_where_predicate_or_recover_tuple_struct_body(
348 struct_: Option<(Ident, Span)>,
351 ) -> PResult<'a, PredicateOrStructBody> {
352 let mut snapshot = None;
354 if let Some(struct_) = struct_
355 && self.may_recover()
356 && self.token.kind == token::OpenDelim(Delimiter::Parenthesis)
358 snapshot = Some((struct_, self.create_snapshot_for_diagnostic()));
361 match self.parse_ty_where_predicate() {
362 Ok(pred) => Ok(PredicateOrStructBody::Predicate(pred)),
364 let Some(((struct_name, body_insertion_point), mut snapshot)) = snapshot else {
365 return Err(type_err);
368 // Check if we might have encountered an out of place tuple struct body.
369 match snapshot.parse_tuple_struct_body() {
370 // Since we don't know the exact reason why we failed to parse the
371 // predicate (we might have stumbled upon something bogus like `(T): ?`),
372 // employ a simple heuristic to weed out some pathological cases:
373 // Look for a semicolon (strong indicator) or anything that might mark
374 // the end of the item (weak indicator) following the body.
376 if matches!(snapshot.token.kind, token::Semi | token::Eof)
377 || snapshot.token.can_begin_item() =>
381 let body_sp = pred_lo.to(snapshot.prev_token.span);
382 let map = self.sess.source_map();
384 self.sess.emit_err(WhereClauseBeforeTupleStructBody {
386 name: struct_name.span,
388 sugg: map.span_to_snippet(body_sp).ok().map(|body| {
389 WhereClauseBeforeTupleStructBodySugg {
390 left: body_insertion_point.shrink_to_hi(),
392 right: map.end_point(where_sp).to(body_sp),
397 self.restore_snapshot(snapshot);
398 Ok(PredicateOrStructBody::StructBody(body))
400 Ok(_) => Err(type_err),
410 fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
411 let lo = self.token.span;
412 // Parse optional `for<'a, 'b>`.
413 // This `for` is parsed greedily and applies to the whole predicate,
414 // the bounded type can have its own `for` applying only to it.
416 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
417 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
418 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
419 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
421 // Parse type with mandatory colon and (possibly empty) bounds,
422 // or with mandatory equality sign and the second type.
423 let ty = self.parse_ty_for_where_clause()?;
424 if self.eat(&token::Colon) {
425 let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
426 Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
427 span: lo.to(self.prev_token.span),
428 bound_generic_params: lifetime_defs,
432 // FIXME: Decide what should be used here, `=` or `==`.
433 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
434 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
435 let rhs_ty = self.parse_ty()?;
436 Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
437 span: lo.to(self.prev_token.span),
442 self.maybe_recover_bounds_doubled_colon(&ty)?;
447 pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
448 // There's an ambiguity between generic parameters and qualified paths in impls.
449 // If we see `<` it may start both, so we have to inspect some following tokens.
450 // The following combinations can only start generics,
451 // but not qualified paths (with one exception):
452 // `<` `>` - empty generic parameters
453 // `<` `#` - generic parameters with attributes
454 // `<` (LIFETIME|IDENT) `>` - single generic parameter
455 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
456 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
457 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
458 // `<` const - generic const parameter
459 // The only truly ambiguous case is
460 // `<` IDENT `>` `::` IDENT ...
461 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
462 // because this is what almost always expected in practice, qualified paths in impls
463 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
464 self.look_ahead(start, |t| t == &token::Lt)
465 && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
466 || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
467 && self.look_ahead(start + 2, |t| {
468 matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
470 || self.is_keyword_ahead(start + 1, &[kw::Const]))