3 use rustc_ast::ast::{self, Attribute, GenericBounds, GenericParam, GenericParamKind, WhereClause};
5 use rustc_errors::PResult;
6 use rustc_span::symbol::{kw, sym};
9 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
12 /// BOUND = LT_BOUND (e.g., `'a`)
14 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
15 let mut lifetimes = Vec::new();
16 while self.check_lifetime() {
17 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
26 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
27 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
28 let ident = self.parse_ident()?;
30 // Parse optional colon and param bounds.
31 let bounds = if self.eat(&token::Colon) {
32 self.parse_generic_bounds(Some(self.prev_token.span))?
37 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
41 id: ast::DUMMY_NODE_ID,
42 attrs: preceding_attrs.into(),
44 kind: GenericParamKind::Type { default },
45 is_placeholder: false,
49 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
50 let const_span = self.token.span;
52 self.expect_keyword(kw::Const)?;
53 let ident = self.parse_ident()?;
54 self.expect(&token::Colon)?;
55 let ty = self.parse_ty()?;
57 self.sess.gated_spans.gate(sym::min_const_generics, const_span.to(self.prev_token.span));
61 id: ast::DUMMY_NODE_ID,
62 attrs: preceding_attrs.into(),
64 kind: GenericParamKind::Const { ty, kw_span: const_span },
65 is_placeholder: false,
69 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
70 /// a trailing comma and erroneous trailing attributes.
71 pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
72 let mut params = Vec::new();
74 let attrs = self.parse_outer_attributes()?;
75 if self.check_lifetime() {
76 let lifetime = self.expect_lifetime();
77 // Parse lifetime parameter.
79 if self.eat(&token::Colon) { self.parse_lt_param_bounds() } else { Vec::new() };
80 params.push(ast::GenericParam {
81 ident: lifetime.ident,
85 kind: ast::GenericParamKind::Lifetime,
86 is_placeholder: false,
88 } else if self.check_keyword(kw::Const) {
89 // Parse const parameter.
90 params.push(self.parse_const_param(attrs)?);
91 } else if self.check_ident() {
92 // Parse type parameter.
93 params.push(self.parse_ty_param(attrs)?);
94 } else if self.token.can_begin_type() {
95 // Trying to write an associated type bound? (#26271)
96 let snapshot = self.clone();
97 match self.parse_ty_where_predicate() {
98 Ok(where_predicate) => {
100 where_predicate.span(),
101 "bounds on associated types do not belong here",
103 .span_label(where_predicate.span(), "belongs in `where` clause")
113 // Check for trailing attributes and stop parsing.
114 if !attrs.is_empty() {
115 if !params.is_empty() {
116 self.struct_span_err(
118 "trailing attribute after generic parameter",
120 .span_label(attrs[0].span, "attributes must go before parameters")
123 self.struct_span_err(attrs[0].span, "attribute without generic parameters")
126 "attributes are only permitted when preceding parameters",
134 if !self.eat(&token::Comma) {
141 /// Parses a set of optional generic type parameter declarations. Where
142 /// clauses are not parsed here, and must be added later via
143 /// `parse_where_clause()`.
145 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
146 /// | ( < lifetimes , typaramseq ( , )? > )
147 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
148 pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
149 let span_lo = self.token.span;
150 let (params, span) = if self.eat_lt() {
151 let params = self.parse_generic_params()?;
153 (params, span_lo.to(self.prev_token.span))
155 (vec![], self.prev_token.span.shrink_to_hi())
159 where_clause: WhereClause {
160 has_where_token: false,
161 predicates: Vec::new(),
162 span: self.prev_token.span.shrink_to_hi(),
168 /// Parses an optional where-clause and places it in `generics`.
170 /// ```ignore (only-for-syntax-highlight)
171 /// where T : Trait<U, V> + 'b, 'a : 'b
173 pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
174 let mut where_clause = WhereClause {
175 has_where_token: false,
176 predicates: Vec::new(),
177 span: self.prev_token.span.shrink_to_hi(),
180 if !self.eat_keyword(kw::Where) {
181 return Ok(where_clause);
183 where_clause.has_where_token = true;
184 let lo = self.prev_token.span;
186 // We are considering adding generics to the `where` keyword as an alternative higher-rank
187 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
188 // change we parse those generics now, but report an error.
189 if self.choose_generics_over_qpath(0) {
190 let generics = self.parse_generics()?;
191 self.struct_span_err(
193 "generic parameters on `where` clauses are reserved for future use",
195 .span_label(generics.span, "currently unsupported")
200 let lo = self.token.span;
201 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
202 let lifetime = self.expect_lifetime();
203 // Bounds starting with a colon are mandatory, but possibly empty.
204 self.expect(&token::Colon)?;
205 let bounds = self.parse_lt_param_bounds();
206 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
207 ast::WhereRegionPredicate {
208 span: lo.to(self.prev_token.span),
213 } else if self.check_type() {
214 where_clause.predicates.push(self.parse_ty_where_predicate()?);
219 if !self.eat(&token::Comma) {
224 where_clause.span = lo.to(self.prev_token.span);
228 fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
229 let lo = self.token.span;
230 // Parse optional `for<'a, 'b>`.
231 // This `for` is parsed greedily and applies to the whole predicate,
232 // the bounded type can have its own `for` applying only to it.
234 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
235 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
236 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
237 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
239 // Parse type with mandatory colon and (possibly empty) bounds,
240 // or with mandatory equality sign and the second type.
241 let ty = self.parse_ty()?;
242 if self.eat(&token::Colon) {
243 let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
244 Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
245 span: lo.to(self.prev_token.span),
246 bound_generic_params: lifetime_defs,
250 // FIXME: Decide what should be used here, `=` or `==`.
251 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
252 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
253 let rhs_ty = self.parse_ty()?;
254 Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
255 span: lo.to(self.prev_token.span),
258 id: ast::DUMMY_NODE_ID,
265 pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
266 // There's an ambiguity between generic parameters and qualified paths in impls.
267 // If we see `<` it may start both, so we have to inspect some following tokens.
268 // The following combinations can only start generics,
269 // but not qualified paths (with one exception):
270 // `<` `>` - empty generic parameters
271 // `<` `#` - generic parameters with attributes
272 // `<` (LIFETIME|IDENT) `>` - single generic parameter
273 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
274 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
275 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
276 // `<` const - generic const parameter
277 // The only truly ambiguous case is
278 // `<` IDENT `>` `::` IDENT ...
279 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
280 // because this is what almost always expected in practice, qualified paths in impls
281 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
282 self.look_ahead(start, |t| t == &token::Lt)
283 && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
284 || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
285 && self.look_ahead(start + 2, |t| {
286 matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
288 || self.is_keyword_ahead(start + 1, &[kw::Const]))