]> git.proxmox.com Git - rustc.git/blame - vendor/rustc-ap-rustc_parse/src/parser/generics.rs
New upstream version 1.52.1+dfsg1
[rustc.git] / vendor / rustc-ap-rustc_parse / src / parser / generics.rs
CommitLineData
f20569fa
XL
1use super::Parser;
2
3use rustc_ast::token;
4use rustc_ast::{
5 self as ast, Attribute, GenericBounds, GenericParam, GenericParamKind, WhereClause,
6};
7use rustc_errors::PResult;
8use rustc_span::symbol::{kw, sym};
9
10impl<'a> Parser<'a> {
11 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
12 ///
13 /// ```text
14 /// BOUND = LT_BOUND (e.g., `'a`)
15 /// ```
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()));
20
21 if !self.eat_plus() {
22 break;
23 }
24 }
25 lifetimes
26 }
27
28 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
29 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
30 let ident = self.parse_ident()?;
31
32 // Parse optional colon and param bounds.
33 let bounds = if self.eat(&token::Colon) {
34 self.parse_generic_bounds(Some(self.prev_token.span))?
35 } else {
36 Vec::new()
37 };
38
39 let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
40
41 Ok(GenericParam {
42 ident,
43 id: ast::DUMMY_NODE_ID,
44 attrs: preceding_attrs.into(),
45 bounds,
46 kind: GenericParamKind::Type { default },
47 is_placeholder: false,
48 })
49 }
50
51 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
52 let const_span = self.token.span;
53
54 self.expect_keyword(kw::Const)?;
55 let ident = self.parse_ident()?;
56 self.expect(&token::Colon)?;
57 let ty = self.parse_ty()?;
58
59 // Parse optional const generics default value, taking care of feature gating the spans
60 // with the unstable syntax mechanism.
61 let default = if self.eat(&token::Eq) {
62 // The gated span goes from the `=` to the end of the const argument that follows (and
63 // which could be a block expression).
64 let start = self.prev_token.span;
65 let const_arg = self.parse_const_arg()?;
66 let span = start.to(const_arg.value.span);
67 self.sess.gated_spans.gate(sym::const_generics_defaults, span);
68 Some(const_arg)
69 } else {
70 None
71 };
72
73 Ok(GenericParam {
74 ident,
75 id: ast::DUMMY_NODE_ID,
76 attrs: preceding_attrs.into(),
77 bounds: Vec::new(),
78 kind: GenericParamKind::Const { ty, kw_span: const_span, default },
79 is_placeholder: false,
80 })
81 }
82
83 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
84 /// a trailing comma and erroneous trailing attributes.
85 pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
86 let mut params = Vec::new();
87 loop {
88 let attrs = self.parse_outer_attributes()?;
89 if self.check_lifetime() {
90 let lifetime = self.expect_lifetime();
91 // Parse lifetime parameter.
92 let bounds =
93 if self.eat(&token::Colon) { self.parse_lt_param_bounds() } else { Vec::new() };
94 params.push(ast::GenericParam {
95 ident: lifetime.ident,
96 id: lifetime.id,
97 attrs: attrs.into(),
98 bounds,
99 kind: ast::GenericParamKind::Lifetime,
100 is_placeholder: false,
101 });
102 } else if self.check_keyword(kw::Const) {
103 // Parse const parameter.
104 params.push(self.parse_const_param(attrs)?);
105 } else if self.check_ident() {
106 // Parse type parameter.
107 params.push(self.parse_ty_param(attrs)?);
108 } else if self.token.can_begin_type() {
109 // Trying to write an associated type bound? (#26271)
110 let snapshot = self.clone();
111 match self.parse_ty_where_predicate() {
112 Ok(where_predicate) => {
113 self.struct_span_err(
114 where_predicate.span(),
115 "bounds on associated types do not belong here",
116 )
117 .span_label(where_predicate.span(), "belongs in `where` clause")
118 .emit();
119 }
120 Err(mut err) => {
121 err.cancel();
122 *self = snapshot;
123 break;
124 }
125 }
126 } else {
127 // Check for trailing attributes and stop parsing.
128 if !attrs.is_empty() {
129 if !params.is_empty() {
130 self.struct_span_err(
131 attrs[0].span,
132 "trailing attribute after generic parameter",
133 )
134 .span_label(attrs[0].span, "attributes must go before parameters")
135 .emit();
136 } else {
137 self.struct_span_err(attrs[0].span, "attribute without generic parameters")
138 .span_label(
139 attrs[0].span,
140 "attributes are only permitted when preceding parameters",
141 )
142 .emit();
143 }
144 }
145 break;
146 }
147
148 if !self.eat(&token::Comma) {
149 break;
150 }
151 }
152 Ok(params)
153 }
154
155 /// Parses a set of optional generic type parameter declarations. Where
156 /// clauses are not parsed here, and must be added later via
157 /// `parse_where_clause()`.
158 ///
159 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
160 /// | ( < lifetimes , typaramseq ( , )? > )
161 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
162 pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
163 let span_lo = self.token.span;
164 let (params, span) = if self.eat_lt() {
165 let params = self.parse_generic_params()?;
166 self.expect_gt()?;
167 (params, span_lo.to(self.prev_token.span))
168 } else {
169 (vec![], self.prev_token.span.shrink_to_hi())
170 };
171 Ok(ast::Generics {
172 params,
173 where_clause: WhereClause {
174 has_where_token: false,
175 predicates: Vec::new(),
176 span: self.prev_token.span.shrink_to_hi(),
177 },
178 span,
179 })
180 }
181
182 /// Parses an optional where-clause and places it in `generics`.
183 ///
184 /// ```ignore (only-for-syntax-highlight)
185 /// where T : Trait<U, V> + 'b, 'a : 'b
186 /// ```
187 pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
188 let mut where_clause = WhereClause {
189 has_where_token: false,
190 predicates: Vec::new(),
191 span: self.prev_token.span.shrink_to_hi(),
192 };
193
194 if !self.eat_keyword(kw::Where) {
195 return Ok(where_clause);
196 }
197 where_clause.has_where_token = true;
198 let lo = self.prev_token.span;
199
200 // We are considering adding generics to the `where` keyword as an alternative higher-rank
201 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
202 // change we parse those generics now, but report an error.
203 if self.choose_generics_over_qpath(0) {
204 let generics = self.parse_generics()?;
205 self.struct_span_err(
206 generics.span,
207 "generic parameters on `where` clauses are reserved for future use",
208 )
209 .span_label(generics.span, "currently unsupported")
210 .emit();
211 }
212
213 loop {
214 let lo = self.token.span;
215 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
216 let lifetime = self.expect_lifetime();
217 // Bounds starting with a colon are mandatory, but possibly empty.
218 self.expect(&token::Colon)?;
219 let bounds = self.parse_lt_param_bounds();
220 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
221 ast::WhereRegionPredicate {
222 span: lo.to(self.prev_token.span),
223 lifetime,
224 bounds,
225 },
226 ));
227 } else if self.check_type() {
228 where_clause.predicates.push(self.parse_ty_where_predicate()?);
229 } else {
230 break;
231 }
232
233 if !self.eat(&token::Comma) {
234 break;
235 }
236 }
237
238 where_clause.span = lo.to(self.prev_token.span);
239 Ok(where_clause)
240 }
241
242 fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
243 let lo = self.token.span;
244 // Parse optional `for<'a, 'b>`.
245 // This `for` is parsed greedily and applies to the whole predicate,
246 // the bounded type can have its own `for` applying only to it.
247 // Examples:
248 // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
249 // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
250 // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
251 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
252
253 // Parse type with mandatory colon and (possibly empty) bounds,
254 // or with mandatory equality sign and the second type.
255 let ty = self.parse_ty_for_where_clause()?;
256 if self.eat(&token::Colon) {
257 let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
258 Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
259 span: lo.to(self.prev_token.span),
260 bound_generic_params: lifetime_defs,
261 bounded_ty: ty,
262 bounds,
263 }))
264 // FIXME: Decide what should be used here, `=` or `==`.
265 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
266 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
267 let rhs_ty = self.parse_ty()?;
268 Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
269 span: lo.to(self.prev_token.span),
270 lhs_ty: ty,
271 rhs_ty,
272 id: ast::DUMMY_NODE_ID,
273 }))
274 } else {
275 self.unexpected()
276 }
277 }
278
279 pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
280 // There's an ambiguity between generic parameters and qualified paths in impls.
281 // If we see `<` it may start both, so we have to inspect some following tokens.
282 // The following combinations can only start generics,
283 // but not qualified paths (with one exception):
284 // `<` `>` - empty generic parameters
285 // `<` `#` - generic parameters with attributes
286 // `<` (LIFETIME|IDENT) `>` - single generic parameter
287 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
288 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
289 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
290 // `<` const - generic const parameter
291 // The only truly ambiguous case is
292 // `<` IDENT `>` `::` IDENT ...
293 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
294 // because this is what almost always expected in practice, qualified paths in impls
295 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
296 self.look_ahead(start, |t| t == &token::Lt)
297 && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
298 || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
299 && self.look_ahead(start + 2, |t| {
300 matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
301 })
302 || self.is_keyword_ahead(start + 1, &[kw::Const]))
303 }
304}