]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/generics.rs
Auto merge of #68351 - Centril:rollup-0gzuh0p, r=Centril
[rust.git] / src / librustc_parse / parser / generics.rs
1 use super::Parser;
2
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};
7 use syntax::token;
8
9 impl<'a> Parser<'a> {
10     /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
11     ///
12     /// ```
13     /// BOUND = LT_BOUND (e.g., `'a`)
14     /// ```
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()));
19
20             if !self.eat_plus() {
21                 break;
22             }
23         }
24         lifetimes
25     }
26
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()?;
30
31         // Parse optional colon and param bounds.
32         let bounds = if self.eat(&token::Colon) {
33             self.parse_generic_bounds(Some(self.prev_span))?
34         } else {
35             Vec::new()
36         };
37
38         let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
39
40         Ok(GenericParam {
41             ident,
42             id: ast::DUMMY_NODE_ID,
43             attrs: preceding_attrs.into(),
44             bounds,
45             kind: GenericParamKind::Type { default },
46             is_placeholder: false,
47         })
48     }
49
50     fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
51         let lo = self.token.span;
52
53         self.expect_keyword(kw::Const)?;
54         let ident = self.parse_ident()?;
55         self.expect(&token::Colon)?;
56         let ty = self.parse_ty()?;
57
58         self.sess.gated_spans.gate(sym::const_generics, lo.to(self.prev_span));
59
60         Ok(GenericParam {
61             ident,
62             id: ast::DUMMY_NODE_ID,
63             attrs: preceding_attrs.into(),
64             bounds: Vec::new(),
65             kind: GenericParamKind::Const { ty },
66             is_placeholder: false,
67         })
68     }
69
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();
74         loop {
75             let attrs = self.parse_outer_attributes()?;
76             if self.check_lifetime() {
77                 let lifetime = self.expect_lifetime();
78                 // Parse lifetime parameter.
79                 let bounds =
80                     if self.eat(&token::Colon) { self.parse_lt_param_bounds() } else { Vec::new() };
81                 params.push(ast::GenericParam {
82                     ident: lifetime.ident,
83                     id: lifetime.id,
84                     attrs: attrs.into(),
85                     bounds,
86                     kind: ast::GenericParamKind::Lifetime,
87                     is_placeholder: false,
88                 });
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",
103                         )
104                         .span_label(where_predicate.span(), "belongs in `where` clause")
105                         .emit();
106                     }
107                     Err(mut err) => {
108                         err.cancel();
109                         std::mem::replace(self, snapshot);
110                         break;
111                     }
112                 }
113             } else {
114                 // Check for trailing attributes and stop parsing.
115                 if !attrs.is_empty() {
116                     if !params.is_empty() {
117                         self.struct_span_err(
118                             attrs[0].span,
119                             "trailing attribute after generic parameter",
120                         )
121                         .span_label(attrs[0].span, "attributes must go before parameters")
122                         .emit();
123                     } else {
124                         self.struct_span_err(
125                             attrs[0].span,
126                             &format!("attribute without generic parameters"),
127                         )
128                         .span_label(
129                             attrs[0].span,
130                             "attributes are only permitted when preceding parameters",
131                         )
132                         .emit();
133                     }
134                 }
135                 break;
136             }
137
138             if !self.eat(&token::Comma) {
139                 break;
140             }
141         }
142         Ok(params)
143     }
144
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()`.
148     ///
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()?;
156             self.expect_gt()?;
157             (params, span_lo.to(self.prev_span))
158         } else {
159             (vec![], self.prev_span.shrink_to_hi())
160         };
161         Ok(ast::Generics {
162             params,
163             where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
164             span,
165         })
166     }
167
168     /// Parses an optional where-clause and places it in `generics`.
169     ///
170     /// ```ignore (only-for-syntax-highlight)
171     /// where T : Trait<U, V> + 'b, 'a : 'b
172     /// ```
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) };
176
177         if !self.eat_keyword(kw::Where) {
178             return Ok(where_clause);
179         }
180         let lo = self.prev_span;
181
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(
188                 generics.span,
189                 "generic parameters on `where` clauses are reserved for future use",
190             )
191             .span_label(generics.span, "currently unsupported")
192             .emit();
193         }
194
195         loop {
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 },
204                 ));
205             } else if self.check_type() {
206                 where_clause.predicates.push(self.parse_ty_where_predicate()?);
207             } else {
208                 break;
209             }
210
211             if !self.eat(&token::Comma) {
212                 break;
213             }
214         }
215
216         where_clause.span = lo.to(self.prev_span);
217         Ok(where_clause)
218     }
219
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.
225         // Examples:
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()?;
230
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,
239                 bounded_ty: ty,
240                 bounds,
241             }))
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),
248                 lhs_ty: ty,
249                 rhs_ty,
250                 id: ast::DUMMY_NODE_ID,
251             }))
252         } else {
253             self.unexpected()
254         }
255     }
256
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| {
278                         t == &token::Gt
279                             || t == &token::Comma
280                             || t == &token::Colon
281                             || t == &token::Eq
282                     })
283                 || self.is_keyword_ahead(1, &[kw::Const]))
284     }
285 }