1 use super::{ForceCollect, Parser, TrailingToken};
5 self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause,
7 use rustc_errors::{Applicability, PResult};
8 use rustc_span::symbol::kw;
11 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
14 /// BOUND = LT_BOUND (e.g., `'a`)
16 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
17 let mut lifetimes = Vec::new();
18 while self.check_lifetime() {
19 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
28 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
29 fn parse_ty_param(&mut self, preceding_attrs: AttrVec) -> PResult<'a, GenericParam> {
30 let ident = self.parse_ident()?;
32 // Parse optional colon and param bounds.
33 let mut colon_span = None;
34 let bounds = if self.eat(&token::Colon) {
35 colon_span = Some(self.prev_token.span);
36 // recover from `impl Trait` in type param bound
37 if self.token.is_keyword(kw::Impl) {
38 let impl_span = self.token.span;
39 let snapshot = self.create_snapshot_for_diagnostic();
40 match self.parse_ty() {
42 if let TyKind::ImplTrait(_, bounds) = &(*p).kind {
43 let span = impl_span.to(self.token.span.shrink_to_lo());
44 let mut err = self.struct_span_err(
46 "expected trait bound, found `impl Trait` type",
48 err.span_label(span, "not a trait");
49 if let [bound, ..] = &bounds[..] {
50 err.span_suggestion_verbose(
51 impl_span.until(bound.span()),
52 "use the trait bounds directly",
54 Applicability::MachineApplicable,
65 self.restore_snapshot(snapshot);
67 self.parse_generic_bounds(colon_span)?
72 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
75 id: ast::DUMMY_NODE_ID,
76 attrs: preceding_attrs,
78 kind: GenericParamKind::Type { default },
79 is_placeholder: false,
84 pub(crate) fn parse_const_param(
86 preceding_attrs: AttrVec,
87 ) -> PResult<'a, GenericParam> {
88 let const_span = self.token.span;
90 self.expect_keyword(kw::Const)?;
91 let ident = self.parse_ident()?;
92 self.expect(&token::Colon)?;
93 let ty = self.parse_ty()?;
95 // Parse optional const generics default value.
96 let default = if self.eat(&token::Eq) { Some(self.parse_const_arg()?) } else { None };
100 id: ast::DUMMY_NODE_ID,
101 attrs: preceding_attrs,
103 kind: GenericParamKind::Const { ty, kw_span: const_span, default },
104 is_placeholder: false,
109 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
110 /// a trailing comma and erroneous trailing attributes.
111 pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
112 let mut params = Vec::new();
113 let mut done = false;
115 let attrs = self.parse_outer_attributes()?;
117 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
118 if this.eat_keyword_noexpect(kw::SelfUpper) {
119 // `Self` as a generic param is invalid. Here we emit the diagnostic and continue parsing
120 // as if `Self` never existed.
121 this.struct_span_err(
122 this.prev_token.span,
123 "unexpected keyword `Self` in generic parameters",
125 .note("you cannot use `Self` as a generic parameter because it is reserved for associated items")
128 this.eat(&token::Comma);
131 let param = if this.check_lifetime() {
132 let lifetime = this.expect_lifetime();
133 // Parse lifetime parameter.
134 let (colon_span, bounds) = if this.eat(&token::Colon) {
135 (Some(this.prev_token.span), this.parse_lt_param_bounds())
139 Some(ast::GenericParam {
140 ident: lifetime.ident,
144 kind: ast::GenericParamKind::Lifetime,
145 is_placeholder: false,
148 } else if this.check_keyword(kw::Const) {
149 // Parse const parameter.
150 Some(this.parse_const_param(attrs)?)
151 } else if this.check_ident() {
152 // Parse type parameter.
153 Some(this.parse_ty_param(attrs)?)
154 } else if this.token.can_begin_type() {
155 // Trying to write an associated type bound? (#26271)
156 let snapshot = this.create_snapshot_for_diagnostic();
157 match this.parse_ty_where_predicate() {
158 Ok(where_predicate) => {
159 this.struct_span_err(
160 where_predicate.span(),
161 "bounds on associated types do not belong here",
163 .span_label(where_predicate.span(), "belongs in `where` clause")
165 // FIXME - try to continue parsing other generics?
166 return Ok((None, TrailingToken::None));
170 // FIXME - maybe we should overwrite 'self' outside of `collect_tokens`?
171 this.restore_snapshot(snapshot);
172 return Ok((None, TrailingToken::None));
176 // Check for trailing attributes and stop parsing.
177 if !attrs.is_empty() {
178 if !params.is_empty() {
179 this.struct_span_err(
181 "trailing attribute after generic parameter",
183 .span_label(attrs[0].span, "attributes must go before parameters")
186 this.struct_span_err(
188 "attribute without generic parameters",
192 "attributes are only permitted when preceding parameters",
197 return Ok((None, TrailingToken::None));
200 if !this.eat(&token::Comma) {
203 // We just ate the comma, so no need to use `TrailingToken`
204 Ok((param, TrailingToken::None))
207 if let Some(param) = param {
216 /// Parses a set of optional generic type parameter declarations. Where
217 /// clauses are not parsed here, and must be added later via
218 /// `parse_where_clause()`.
220 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
221 /// | ( < lifetimes , typaramseq ( , )? > )
222 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
223 pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
224 let span_lo = self.token.span;
225 let (params, span) = if self.eat_lt() {
226 let params = self.parse_generic_params()?;
228 (params, span_lo.to(self.prev_token.span))
230 (vec![], self.prev_token.span.shrink_to_hi())
234 where_clause: WhereClause {
235 has_where_token: false,
236 predicates: Vec::new(),
237 span: self.prev_token.span.shrink_to_hi(),
243 /// Parses an optional where-clause and places it in `generics`.
245 /// ```ignore (only-for-syntax-highlight)
246 /// where T : Trait<U, V> + 'b, 'a : 'b
248 pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
249 let mut where_clause = WhereClause {
250 has_where_token: false,
251 predicates: Vec::new(),
252 span: self.prev_token.span.shrink_to_hi(),
255 if !self.eat_keyword(kw::Where) {
256 return Ok(where_clause);
258 where_clause.has_where_token = true;
259 let lo = self.prev_token.span;
261 // We are considering adding generics to the `where` keyword as an alternative higher-rank
262 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
263 // change we parse those generics now, but report an error.
264 if self.choose_generics_over_qpath(0) {
265 let generics = self.parse_generics()?;
266 self.struct_span_err(
268 "generic parameters on `where` clauses are reserved for future use",
270 .span_label(generics.span, "currently unsupported")
275 let lo = self.token.span;
276 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
277 let lifetime = self.expect_lifetime();
278 // Bounds starting with a colon are mandatory, but possibly empty.
279 self.expect(&token::Colon)?;
280 let bounds = self.parse_lt_param_bounds();
281 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
282 ast::WhereRegionPredicate {
283 span: lo.to(self.prev_token.span),
288 } else if self.check_type() {
289 where_clause.predicates.push(self.parse_ty_where_predicate()?);
294 let prev_token = self.prev_token.span;
295 let ate_comma = self.eat(&token::Comma);
297 if self.eat_keyword_noexpect(kw::Where) {
298 let msg = "cannot define duplicate `where` clauses on an item";
299 let mut err = self.struct_span_err(self.token.span, msg);
300 err.span_label(lo, "previous `where` clause starts here");
301 err.span_suggestion_verbose(
302 prev_token.shrink_to_hi().to(self.prev_token.span),
303 "consider joining the two `where` clauses into one",
305 Applicability::MaybeIncorrect,
308 } else if !ate_comma {
313 where_clause.span = lo.to(self.prev_token.span);
317 fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
318 let lo = self.token.span;
319 // Parse optional `for<'a, 'b>`.
320 // This `for` is parsed greedily and applies to the whole predicate,
321 // the bounded type can have its own `for` applying only to it.
323 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
324 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
325 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
326 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
328 // Parse type with mandatory colon and (possibly empty) bounds,
329 // or with mandatory equality sign and the second type.
330 let ty = self.parse_ty_for_where_clause()?;
331 if self.eat(&token::Colon) {
332 let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
333 Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
334 span: lo.to(self.prev_token.span),
335 bound_generic_params: lifetime_defs,
339 // FIXME: Decide what should be used here, `=` or `==`.
340 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
341 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
342 let rhs_ty = self.parse_ty()?;
343 Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
344 span: lo.to(self.prev_token.span),
349 self.maybe_recover_bounds_doubled_colon(&ty)?;
354 pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
355 // There's an ambiguity between generic parameters and qualified paths in impls.
356 // If we see `<` it may start both, so we have to inspect some following tokens.
357 // The following combinations can only start generics,
358 // but not qualified paths (with one exception):
359 // `<` `>` - empty generic parameters
360 // `<` `#` - generic parameters with attributes
361 // `<` (LIFETIME|IDENT) `>` - single generic parameter
362 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
363 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
364 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
365 // `<` const - generic const parameter
366 // The only truly ambiguous case is
367 // `<` IDENT `>` `::` IDENT ...
368 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
369 // because this is what almost always expected in practice, qualified paths in impls
370 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
371 self.look_ahead(start, |t| t == &token::Lt)
372 && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
373 || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
374 && self.look_ahead(start + 2, |t| {
375 matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
377 || self.is_keyword_ahead(start + 1, &[kw::Const]))