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 lo = 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::const_generics, lo.to(self.prev_token.span));
61 id: ast::DUMMY_NODE_ID,
62 attrs: preceding_attrs.into(),
64 kind: GenericParamKind::Const { ty },
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")
108 std::mem::replace(self, snapshot);
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 predicates: Vec::new(),
161 span: self.prev_token.span.shrink_to_hi(),
167 /// Parses an optional where-clause and places it in `generics`.
169 /// ```ignore (only-for-syntax-highlight)
170 /// where T : Trait<U, V> + 'b, 'a : 'b
172 pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
173 let mut where_clause =
174 WhereClause { predicates: Vec::new(), span: self.prev_token.span.shrink_to_hi() };
176 if !self.eat_keyword(kw::Where) {
177 return Ok(where_clause);
179 let lo = self.prev_token.span;
181 // We are considering adding generics to the `where` keyword as an alternative higher-rank
182 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
183 // change we parse those generics now, but report an error.
184 if self.choose_generics_over_qpath() {
185 let generics = self.parse_generics()?;
186 self.struct_span_err(
188 "generic parameters on `where` clauses are reserved for future use",
190 .span_label(generics.span, "currently unsupported")
195 let lo = self.token.span;
196 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
197 let lifetime = self.expect_lifetime();
198 // Bounds starting with a colon are mandatory, but possibly empty.
199 self.expect(&token::Colon)?;
200 let bounds = self.parse_lt_param_bounds();
201 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
202 ast::WhereRegionPredicate {
203 span: lo.to(self.prev_token.span),
208 } else if self.check_type() {
209 where_clause.predicates.push(self.parse_ty_where_predicate()?);
214 if !self.eat(&token::Comma) {
219 where_clause.span = lo.to(self.prev_token.span);
223 fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
224 let lo = self.token.span;
225 // Parse optional `for<'a, 'b>`.
226 // This `for` is parsed greedily and applies to the whole predicate,
227 // the bounded type can have its own `for` applying only to it.
229 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
230 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
231 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
232 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
234 // Parse type with mandatory colon and (possibly empty) bounds,
235 // or with mandatory equality sign and the second type.
236 let ty = self.parse_ty()?;
237 if self.eat(&token::Colon) {
238 let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
239 Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
240 span: lo.to(self.prev_token.span),
241 bound_generic_params: lifetime_defs,
245 // FIXME: Decide what should be used here, `=` or `==`.
246 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
247 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
248 let rhs_ty = self.parse_ty()?;
249 Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
250 span: lo.to(self.prev_token.span),
253 id: ast::DUMMY_NODE_ID,
260 pub(super) fn choose_generics_over_qpath(&self) -> bool {
261 // There's an ambiguity between generic parameters and qualified paths in impls.
262 // If we see `<` it may start both, so we have to inspect some following tokens.
263 // The following combinations can only start generics,
264 // but not qualified paths (with one exception):
265 // `<` `>` - empty generic parameters
266 // `<` `#` - generic parameters with attributes
267 // `<` (LIFETIME|IDENT) `>` - single generic parameter
268 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
269 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
270 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
271 // `<` const - generic const parameter
272 // The only truly ambiguous case is
273 // `<` IDENT `>` `::` IDENT ...
274 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
275 // because this is what almost always expected in practice, qualified paths in impls
276 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
277 self.token == token::Lt
278 && (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt)
279 || self.look_ahead(1, |t| t.is_lifetime() || t.is_ident())
280 && self.look_ahead(2, |t| {
282 || t == &token::Comma
283 || t == &token::Colon
286 || self.is_keyword_ahead(1, &[kw::Const]))