3 use rustc_errors::PResult;
4 use rustc_span::source_map::DUMMY_SP;
5 use rustc_span::symbol::{kw, sym};
6 use syntax::ast::{self, Attribute, GenericBounds, GenericParam, GenericParamKind, WhereClause};
10 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
13 /// BOUND = LT_BOUND (e.g., `'a`)
15 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
16 let mut lifetimes = Vec::new();
17 while self.check_lifetime() {
18 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
27 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
28 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
29 let ident = self.parse_ident()?;
31 // Parse optional colon and param bounds.
32 let bounds = if self.eat(&token::Colon) {
33 self.parse_generic_bounds(Some(self.prev_span))?
38 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
42 id: ast::DUMMY_NODE_ID,
43 attrs: preceding_attrs.into(),
45 kind: GenericParamKind::Type { default },
46 is_placeholder: false,
50 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
51 let lo = self.token.span;
53 self.expect_keyword(kw::Const)?;
54 let ident = self.parse_ident()?;
55 self.expect(&token::Colon)?;
56 let ty = self.parse_ty()?;
58 self.sess.gated_spans.gate(sym::const_generics, lo.to(self.prev_span));
62 id: ast::DUMMY_NODE_ID,
63 attrs: preceding_attrs.into(),
65 kind: GenericParamKind::Const { ty },
66 is_placeholder: false,
70 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
71 /// a trailing comma and erroneous trailing attributes.
72 pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
73 let mut params = Vec::new();
75 let attrs = self.parse_outer_attributes()?;
76 if self.check_lifetime() {
77 let lifetime = self.expect_lifetime();
78 // Parse lifetime parameter.
80 if self.eat(&token::Colon) { self.parse_lt_param_bounds() } else { Vec::new() };
81 params.push(ast::GenericParam {
82 ident: lifetime.ident,
86 kind: ast::GenericParamKind::Lifetime,
87 is_placeholder: false,
89 } else if self.check_keyword(kw::Const) {
90 // Parse const parameter.
91 params.push(self.parse_const_param(attrs)?);
92 } else if self.check_ident() {
93 // Parse type parameter.
94 params.push(self.parse_ty_param(attrs)?);
95 } else if self.token.can_begin_type() {
96 // Trying to write an associated type bound? (#26271)
97 let snapshot = self.clone();
98 match self.parse_ty_where_predicate() {
99 Ok(where_predicate) => {
100 self.struct_span_err(
101 where_predicate.span(),
102 "bounds on associated types do not belong here",
104 .span_label(where_predicate.span(), "belongs in `where` clause")
109 std::mem::replace(self, snapshot);
114 // Check for trailing attributes and stop parsing.
115 if !attrs.is_empty() {
116 if !params.is_empty() {
117 self.struct_span_err(
119 "trailing attribute after generic parameter",
121 .span_label(attrs[0].span, "attributes must go before parameters")
124 self.struct_span_err(
126 &format!("attribute without generic parameters"),
130 "attributes are only permitted when preceding parameters",
138 if !self.eat(&token::Comma) {
145 /// Parses a set of optional generic type parameter declarations. Where
146 /// clauses are not parsed here, and must be added later via
147 /// `parse_where_clause()`.
149 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
150 /// | ( < lifetimes , typaramseq ( , )? > )
151 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
152 pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
153 let span_lo = self.token.span;
154 let (params, span) = if self.eat_lt() {
155 let params = self.parse_generic_params()?;
157 (params, span_lo.to(self.prev_span))
159 (vec![], self.prev_span.shrink_to_hi())
163 where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
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 =
175 WhereClause { predicates: Vec::new(), span: self.prev_span.to(self.prev_span) };
177 if !self.eat_keyword(kw::Where) {
178 return Ok(where_clause);
180 let lo = self.prev_span;
182 // We are considering adding generics to the `where` keyword as an alternative higher-rank
183 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
184 // change we parse those generics now, but report an error.
185 if self.choose_generics_over_qpath() {
186 let generics = self.parse_generics()?;
187 self.struct_span_err(
189 "generic parameters on `where` clauses are reserved for future use",
191 .span_label(generics.span, "currently unsupported")
196 let lo = self.token.span;
197 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
198 let lifetime = self.expect_lifetime();
199 // Bounds starting with a colon are mandatory, but possibly empty.
200 self.expect(&token::Colon)?;
201 let bounds = self.parse_lt_param_bounds();
202 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
203 ast::WhereRegionPredicate { span: lo.to(self.prev_span), lifetime, bounds },
205 } else if self.check_type() {
206 where_clause.predicates.push(self.parse_ty_where_predicate()?);
211 if !self.eat(&token::Comma) {
216 where_clause.span = lo.to(self.prev_span);
220 fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
221 let lo = self.token.span;
222 // Parse optional `for<'a, 'b>`.
223 // This `for` is parsed greedily and applies to the whole predicate,
224 // the bounded type can have its own `for` applying only to it.
226 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
227 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
228 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
229 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
231 // Parse type with mandatory colon and (possibly empty) bounds,
232 // or with mandatory equality sign and the second type.
233 let ty = self.parse_ty()?;
234 if self.eat(&token::Colon) {
235 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
236 Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
237 span: lo.to(self.prev_span),
238 bound_generic_params: lifetime_defs,
242 // FIXME: Decide what should be used here, `=` or `==`.
243 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
244 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
245 let rhs_ty = self.parse_ty()?;
246 Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
247 span: lo.to(self.prev_span),
250 id: ast::DUMMY_NODE_ID,
257 pub(super) fn choose_generics_over_qpath(&self) -> bool {
258 // There's an ambiguity between generic parameters and qualified paths in impls.
259 // If we see `<` it may start both, so we have to inspect some following tokens.
260 // The following combinations can only start generics,
261 // but not qualified paths (with one exception):
262 // `<` `>` - empty generic parameters
263 // `<` `#` - generic parameters with attributes
264 // `<` (LIFETIME|IDENT) `>` - single generic parameter
265 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
266 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
267 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
268 // `<` const - generic const parameter
269 // The only truly ambiguous case is
270 // `<` IDENT `>` `::` IDENT ...
271 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
272 // because this is what almost always expected in practice, qualified paths in impls
273 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
274 self.token == token::Lt
275 && (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt)
276 || self.look_ahead(1, |t| t.is_lifetime() || t.is_ident())
277 && self.look_ahead(2, |t| {
279 || t == &token::Comma
280 || t == &token::Colon
283 || self.is_keyword_ahead(1, &[kw::Const]))