]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/generics.rs
Migrate `rustc_parse` to derive diagnostics
[rust.git] / compiler / rustc_parse / src / parser / generics.rs
1 use crate::errors::{
2     MultipleWhereClauses, UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody,
3     WhereClauseBeforeTupleStructBodySugg,
4 };
5
6 use super::{ForceCollect, Parser, TrailingToken};
7
8 use ast::token::Delimiter;
9 use rustc_ast::token;
10 use rustc_ast::{
11     self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause,
12 };
13 use rustc_errors::{Applicability, PResult};
14 use rustc_span::symbol::{kw, Ident};
15 use rustc_span::Span;
16
17 enum PredicateOrStructBody {
18     Predicate(ast::WherePredicate),
19     StructBody(Vec<ast::FieldDef>),
20 }
21
22 impl<'a> Parser<'a> {
23     /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
24     ///
25     /// ```text
26     /// BOUND = LT_BOUND (e.g., `'a`)
27     /// ```
28     fn parse_lt_param_bounds(&mut self) -> GenericBounds {
29         let mut lifetimes = Vec::new();
30         while self.check_lifetime() {
31             lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
32
33             if !self.eat_plus() {
34                 break;
35             }
36         }
37         lifetimes
38     }
39
40     /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
41     fn parse_ty_param(&mut self, preceding_attrs: AttrVec) -> PResult<'a, GenericParam> {
42         let ident = self.parse_ident()?;
43
44         // Parse optional colon and param bounds.
45         let mut colon_span = None;
46         let bounds = if self.eat(&token::Colon) {
47             colon_span = Some(self.prev_token.span);
48             // recover from `impl Trait` in type param bound
49             if self.token.is_keyword(kw::Impl) {
50                 let impl_span = self.token.span;
51                 let snapshot = self.create_snapshot_for_diagnostic();
52                 match self.parse_ty() {
53                     Ok(p) => {
54                         if let TyKind::ImplTrait(_, bounds) = &(*p).kind {
55                             let span = impl_span.to(self.token.span.shrink_to_lo());
56                             let mut err = self.struct_span_err(
57                                 span,
58                                 "expected trait bound, found `impl Trait` type",
59                             );
60                             err.span_label(span, "not a trait");
61                             if let [bound, ..] = &bounds[..] {
62                                 err.span_suggestion_verbose(
63                                     impl_span.until(bound.span()),
64                                     "use the trait bounds directly",
65                                     String::new(),
66                                     Applicability::MachineApplicable,
67                                 );
68                             }
69                             err.emit();
70                             return Err(err);
71                         }
72                     }
73                     Err(err) => {
74                         err.cancel();
75                     }
76                 }
77                 self.restore_snapshot(snapshot);
78             }
79             self.parse_generic_bounds(colon_span)?
80         } else {
81             Vec::new()
82         };
83
84         let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
85         Ok(GenericParam {
86             ident,
87             id: ast::DUMMY_NODE_ID,
88             attrs: preceding_attrs,
89             bounds,
90             kind: GenericParamKind::Type { default },
91             is_placeholder: false,
92             colon_span,
93         })
94     }
95
96     pub(crate) fn parse_const_param(
97         &mut self,
98         preceding_attrs: AttrVec,
99     ) -> PResult<'a, GenericParam> {
100         let const_span = self.token.span;
101
102         self.expect_keyword(kw::Const)?;
103         let ident = self.parse_ident()?;
104         self.expect(&token::Colon)?;
105         let ty = self.parse_ty()?;
106
107         // Parse optional const generics default value.
108         let default = if self.eat(&token::Eq) { Some(self.parse_const_arg()?) } else { None };
109
110         Ok(GenericParam {
111             ident,
112             id: ast::DUMMY_NODE_ID,
113             attrs: preceding_attrs,
114             bounds: Vec::new(),
115             kind: GenericParamKind::Const { ty, kw_span: const_span, default },
116             is_placeholder: false,
117             colon_span: None,
118         })
119     }
120
121     /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
122     /// a trailing comma and erroneous trailing attributes.
123     pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
124         let mut params = Vec::new();
125         let mut done = false;
126         while !done {
127             let attrs = self.parse_outer_attributes()?;
128             let param =
129                 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
130                     if this.eat_keyword_noexpect(kw::SelfUpper) {
131                         // `Self` as a generic param is invalid. Here we emit the diagnostic and continue parsing
132                         // as if `Self` never existed.
133                         this.sess.emit_err(UnexpectedSelfInGenericParameters {
134                             span: this.prev_token.span,
135                         });
136
137                         this.eat(&token::Comma);
138                     }
139
140                     let param = if this.check_lifetime() {
141                         let lifetime = this.expect_lifetime();
142                         // Parse lifetime parameter.
143                         let (colon_span, bounds) = if this.eat(&token::Colon) {
144                             (Some(this.prev_token.span), this.parse_lt_param_bounds())
145                         } else {
146                             (None, Vec::new())
147                         };
148                         Some(ast::GenericParam {
149                             ident: lifetime.ident,
150                             id: lifetime.id,
151                             attrs,
152                             bounds,
153                             kind: ast::GenericParamKind::Lifetime,
154                             is_placeholder: false,
155                             colon_span,
156                         })
157                     } else if this.check_keyword(kw::Const) {
158                         // Parse const parameter.
159                         Some(this.parse_const_param(attrs)?)
160                     } else if this.check_ident() {
161                         // Parse type parameter.
162                         Some(this.parse_ty_param(attrs)?)
163                     } else if this.token.can_begin_type() {
164                         // Trying to write an associated type bound? (#26271)
165                         let snapshot = this.create_snapshot_for_diagnostic();
166                         match this.parse_ty_where_predicate() {
167                             Ok(where_predicate) => {
168                                 this.struct_span_err(
169                                     where_predicate.span(),
170                                     "bounds on associated types do not belong here",
171                                 )
172                                 .span_label(where_predicate.span(), "belongs in `where` clause")
173                                 .emit();
174                                 // FIXME - try to continue parsing other generics?
175                                 return Ok((None, TrailingToken::None));
176                             }
177                             Err(err) => {
178                                 err.cancel();
179                                 // FIXME - maybe we should overwrite 'self' outside of `collect_tokens`?
180                                 this.restore_snapshot(snapshot);
181                                 return Ok((None, TrailingToken::None));
182                             }
183                         }
184                     } else {
185                         // Check for trailing attributes and stop parsing.
186                         if !attrs.is_empty() {
187                             if !params.is_empty() {
188                                 this.struct_span_err(
189                                     attrs[0].span,
190                                     "trailing attribute after generic parameter",
191                                 )
192                                 .span_label(attrs[0].span, "attributes must go before parameters")
193                                 .emit();
194                             } else {
195                                 this.struct_span_err(
196                                     attrs[0].span,
197                                     "attribute without generic parameters",
198                                 )
199                                 .span_label(
200                                     attrs[0].span,
201                                     "attributes are only permitted when preceding parameters",
202                                 )
203                                 .emit();
204                             }
205                         }
206                         return Ok((None, TrailingToken::None));
207                     };
208
209                     if !this.eat(&token::Comma) {
210                         done = true;
211                     }
212                     // We just ate the comma, so no need to use `TrailingToken`
213                     Ok((param, TrailingToken::None))
214                 })?;
215
216             if let Some(param) = param {
217                 params.push(param);
218             } else {
219                 break;
220             }
221         }
222         Ok(params)
223     }
224
225     /// Parses a set of optional generic type parameter declarations. Where
226     /// clauses are not parsed here, and must be added later via
227     /// `parse_where_clause()`.
228     ///
229     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
230     ///                  | ( < lifetimes , typaramseq ( , )? > )
231     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
232     pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
233         let span_lo = self.token.span;
234         let (params, span) = if self.eat_lt() {
235             let params = self.parse_generic_params()?;
236             self.expect_gt()?;
237             (params, span_lo.to(self.prev_token.span))
238         } else {
239             (vec![], self.prev_token.span.shrink_to_hi())
240         };
241         Ok(ast::Generics {
242             params,
243             where_clause: WhereClause {
244                 has_where_token: false,
245                 predicates: Vec::new(),
246                 span: self.prev_token.span.shrink_to_hi(),
247             },
248             span,
249         })
250     }
251
252     /// Parses an optional where-clause.
253     ///
254     /// ```ignore (only-for-syntax-highlight)
255     /// where T : Trait<U, V> + 'b, 'a : 'b
256     /// ```
257     pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
258         self.parse_where_clause_common(None).map(|(clause, _)| clause)
259     }
260
261     pub(super) fn parse_struct_where_clause(
262         &mut self,
263         struct_name: Ident,
264         body_insertion_point: Span,
265     ) -> PResult<'a, (WhereClause, Option<Vec<ast::FieldDef>>)> {
266         self.parse_where_clause_common(Some((struct_name, body_insertion_point)))
267     }
268
269     fn parse_where_clause_common(
270         &mut self,
271         struct_: Option<(Ident, Span)>,
272     ) -> PResult<'a, (WhereClause, Option<Vec<ast::FieldDef>>)> {
273         let mut where_clause = WhereClause {
274             has_where_token: false,
275             predicates: Vec::new(),
276             span: self.prev_token.span.shrink_to_hi(),
277         };
278         let mut tuple_struct_body = None;
279
280         if !self.eat_keyword(kw::Where) {
281             return Ok((where_clause, None));
282         }
283         where_clause.has_where_token = true;
284         let where_lo = self.prev_token.span;
285
286         // We are considering adding generics to the `where` keyword as an alternative higher-rank
287         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
288         // change we parse those generics now, but report an error.
289         if self.choose_generics_over_qpath(0) {
290             let generics = self.parse_generics()?;
291             self.struct_span_err(
292                 generics.span,
293                 "generic parameters on `where` clauses are reserved for future use",
294             )
295             .span_label(generics.span, "currently unsupported")
296             .emit();
297         }
298
299         loop {
300             let where_sp = where_lo.to(self.prev_token.span);
301             let pred_lo = self.token.span;
302             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
303                 let lifetime = self.expect_lifetime();
304                 // Bounds starting with a colon are mandatory, but possibly empty.
305                 self.expect(&token::Colon)?;
306                 let bounds = self.parse_lt_param_bounds();
307                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
308                     ast::WhereRegionPredicate {
309                         span: pred_lo.to(self.prev_token.span),
310                         lifetime,
311                         bounds,
312                     },
313                 ));
314             } else if self.check_type() {
315                 match self.parse_ty_where_predicate_or_recover_tuple_struct_body(
316                     struct_, pred_lo, where_sp,
317                 )? {
318                     PredicateOrStructBody::Predicate(pred) => where_clause.predicates.push(pred),
319                     PredicateOrStructBody::StructBody(body) => {
320                         tuple_struct_body = Some(body);
321                         break;
322                     }
323                 }
324             } else {
325                 break;
326             }
327
328             let prev_token = self.prev_token.span;
329             let ate_comma = self.eat(&token::Comma);
330
331             if self.eat_keyword_noexpect(kw::Where) {
332                 self.sess.emit_err(MultipleWhereClauses {
333                     span: self.token.span,
334                     previous: pred_lo,
335                     between: prev_token.shrink_to_hi().to(self.prev_token.span),
336                 });
337             } else if !ate_comma {
338                 break;
339             }
340         }
341
342         where_clause.span = where_lo.to(self.prev_token.span);
343         Ok((where_clause, tuple_struct_body))
344     }
345
346     fn parse_ty_where_predicate_or_recover_tuple_struct_body(
347         &mut self,
348         struct_: Option<(Ident, Span)>,
349         pred_lo: Span,
350         where_sp: Span,
351     ) -> PResult<'a, PredicateOrStructBody> {
352         let mut snapshot = None;
353
354         if let Some(struct_) = struct_
355             && self.may_recover()
356             && self.token.kind == token::OpenDelim(Delimiter::Parenthesis)
357         {
358             snapshot = Some((struct_, self.create_snapshot_for_diagnostic()));
359         };
360
361         match self.parse_ty_where_predicate() {
362             Ok(pred) => Ok(PredicateOrStructBody::Predicate(pred)),
363             Err(type_err) => {
364                 let Some(((struct_name, body_insertion_point), mut snapshot)) = snapshot else {
365                     return Err(type_err);
366                 };
367
368                 // Check if we might have encountered an out of place tuple struct body.
369                 match snapshot.parse_tuple_struct_body() {
370                     // Since we don't know the exact reason why we failed to parse the
371                     // predicate (we might have stumbled upon something bogus like `(T): ?`),
372                     // employ a simple heuristic to weed out some pathological cases:
373                     // Look for a semicolon (strong indicator) or anything that might mark
374                     // the end of the item (weak indicator) following the body.
375                     Ok(body)
376                         if matches!(snapshot.token.kind, token::Semi | token::Eof)
377                             || snapshot.token.can_begin_item() =>
378                     {
379                         type_err.cancel();
380
381                         let body_sp = pred_lo.to(snapshot.prev_token.span);
382                         let map = self.sess.source_map();
383
384                         self.sess.emit_err(WhereClauseBeforeTupleStructBody {
385                             span: where_sp,
386                             name: struct_name.span,
387                             body: body_sp,
388                             sugg: map.span_to_snippet(body_sp).ok().map(|body| {
389                                 WhereClauseBeforeTupleStructBodySugg {
390                                     left: body_insertion_point.shrink_to_hi(),
391                                     snippet: body,
392                                     right: map.end_point(where_sp).to(body_sp),
393                                 }
394                             }),
395                         });
396
397                         self.restore_snapshot(snapshot);
398                         Ok(PredicateOrStructBody::StructBody(body))
399                     }
400                     Ok(_) => Err(type_err),
401                     Err(body_err) => {
402                         body_err.cancel();
403                         Err(type_err)
404                     }
405                 }
406             }
407         }
408     }
409
410     fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
411         let lo = self.token.span;
412         // Parse optional `for<'a, 'b>`.
413         // This `for` is parsed greedily and applies to the whole predicate,
414         // the bounded type can have its own `for` applying only to it.
415         // Examples:
416         // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
417         // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
418         // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
419         let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
420
421         // Parse type with mandatory colon and (possibly empty) bounds,
422         // or with mandatory equality sign and the second type.
423         let ty = self.parse_ty_for_where_clause()?;
424         if self.eat(&token::Colon) {
425             let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
426             Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
427                 span: lo.to(self.prev_token.span),
428                 bound_generic_params: lifetime_defs,
429                 bounded_ty: ty,
430                 bounds,
431             }))
432         // FIXME: Decide what should be used here, `=` or `==`.
433         // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
434         } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
435             let rhs_ty = self.parse_ty()?;
436             Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
437                 span: lo.to(self.prev_token.span),
438                 lhs_ty: ty,
439                 rhs_ty,
440             }))
441         } else {
442             self.maybe_recover_bounds_doubled_colon(&ty)?;
443             self.unexpected()
444         }
445     }
446
447     pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
448         // There's an ambiguity between generic parameters and qualified paths in impls.
449         // If we see `<` it may start both, so we have to inspect some following tokens.
450         // The following combinations can only start generics,
451         // but not qualified paths (with one exception):
452         //     `<` `>` - empty generic parameters
453         //     `<` `#` - generic parameters with attributes
454         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
455         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
456         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
457         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
458         //     `<` const                - generic const parameter
459         // The only truly ambiguous case is
460         //     `<` IDENT `>` `::` IDENT ...
461         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
462         // because this is what almost always expected in practice, qualified paths in impls
463         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
464         self.look_ahead(start, |t| t == &token::Lt)
465             && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
466                 || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
467                     && self.look_ahead(start + 2, |t| {
468                         matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
469                     })
470                 || self.is_keyword_ahead(start + 1, &[kw::Const]))
471     }
472 }