]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/generics.rs
ast: Implement `TryFrom<ItemKind>` for associated and foreign items
[rust.git] / src / librustc_parse / parser / generics.rs
1 use super::Parser;
2
3 use rustc_ast::ast::{self, Attribute, GenericBounds, GenericParam, GenericParamKind, WhereClause};
4 use rustc_ast::token;
5 use rustc_errors::PResult;
6 use rustc_span::symbol::{kw, sym};
7
8 impl<'a> Parser<'a> {
9     /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
10     ///
11     /// ```
12     /// BOUND = LT_BOUND (e.g., `'a`)
13     /// ```
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()));
18
19             if !self.eat_plus() {
20                 break;
21             }
22         }
23         lifetimes
24     }
25
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()?;
29
30         // Parse optional colon and param bounds.
31         let bounds = if self.eat(&token::Colon) {
32             self.parse_generic_bounds(Some(self.prev_span))?
33         } else {
34             Vec::new()
35         };
36
37         let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
38
39         Ok(GenericParam {
40             ident,
41             id: ast::DUMMY_NODE_ID,
42             attrs: preceding_attrs.into(),
43             bounds,
44             kind: GenericParamKind::Type { default },
45             is_placeholder: false,
46         })
47     }
48
49     fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
50         let lo = self.token.span;
51
52         self.expect_keyword(kw::Const)?;
53         let ident = self.parse_ident()?;
54         self.expect(&token::Colon)?;
55         let ty = self.parse_ty()?;
56
57         self.sess.gated_spans.gate(sym::const_generics, lo.to(self.prev_span));
58
59         Ok(GenericParam {
60             ident,
61             id: ast::DUMMY_NODE_ID,
62             attrs: preceding_attrs.into(),
63             bounds: Vec::new(),
64             kind: GenericParamKind::Const { ty },
65             is_placeholder: false,
66         })
67     }
68
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();
73         loop {
74             let attrs = self.parse_outer_attributes()?;
75             if self.check_lifetime() {
76                 let lifetime = self.expect_lifetime();
77                 // Parse lifetime parameter.
78                 let bounds =
79                     if self.eat(&token::Colon) { self.parse_lt_param_bounds() } else { Vec::new() };
80                 params.push(ast::GenericParam {
81                     ident: lifetime.ident,
82                     id: lifetime.id,
83                     attrs: attrs.into(),
84                     bounds,
85                     kind: ast::GenericParamKind::Lifetime,
86                     is_placeholder: false,
87                 });
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) => {
99                         self.struct_span_err(
100                             where_predicate.span(),
101                             "bounds on associated types do not belong here",
102                         )
103                         .span_label(where_predicate.span(), "belongs in `where` clause")
104                         .emit();
105                     }
106                     Err(mut err) => {
107                         err.cancel();
108                         std::mem::replace(self, snapshot);
109                         break;
110                     }
111                 }
112             } else {
113                 // Check for trailing attributes and stop parsing.
114                 if !attrs.is_empty() {
115                     if !params.is_empty() {
116                         self.struct_span_err(
117                             attrs[0].span,
118                             "trailing attribute after generic parameter",
119                         )
120                         .span_label(attrs[0].span, "attributes must go before parameters")
121                         .emit();
122                     } else {
123                         self.struct_span_err(attrs[0].span, "attribute without generic parameters")
124                             .span_label(
125                                 attrs[0].span,
126                                 "attributes are only permitted when preceding parameters",
127                             )
128                             .emit();
129                     }
130                 }
131                 break;
132             }
133
134             if !self.eat(&token::Comma) {
135                 break;
136             }
137         }
138         Ok(params)
139     }
140
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()`.
144     ///
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()?;
152             self.expect_gt()?;
153             (params, span_lo.to(self.prev_span))
154         } else {
155             (vec![], self.prev_span.shrink_to_hi())
156         };
157         Ok(ast::Generics {
158             params,
159             where_clause: WhereClause {
160                 predicates: Vec::new(),
161                 span: self.prev_span.shrink_to_hi(),
162             },
163             span,
164         })
165     }
166
167     /// Parses an optional where-clause and places it in `generics`.
168     ///
169     /// ```ignore (only-for-syntax-highlight)
170     /// where T : Trait<U, V> + 'b, 'a : 'b
171     /// ```
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_span.shrink_to_hi() };
175
176         if !self.eat_keyword(kw::Where) {
177             return Ok(where_clause);
178         }
179         let lo = self.prev_span;
180
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(
187                 generics.span,
188                 "generic parameters on `where` clauses are reserved for future use",
189             )
190             .span_label(generics.span, "currently unsupported")
191             .emit();
192         }
193
194         loop {
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 { span: lo.to(self.prev_span), lifetime, bounds },
203                 ));
204             } else if self.check_type() {
205                 where_clause.predicates.push(self.parse_ty_where_predicate()?);
206             } else {
207                 break;
208             }
209
210             if !self.eat(&token::Comma) {
211                 break;
212             }
213         }
214
215         where_clause.span = lo.to(self.prev_span);
216         Ok(where_clause)
217     }
218
219     fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
220         let lo = self.token.span;
221         // Parse optional `for<'a, 'b>`.
222         // This `for` is parsed greedily and applies to the whole predicate,
223         // the bounded type can have its own `for` applying only to it.
224         // Examples:
225         // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
226         // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
227         // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
228         let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
229
230         // Parse type with mandatory colon and (possibly empty) bounds,
231         // or with mandatory equality sign and the second type.
232         let ty = self.parse_ty()?;
233         if self.eat(&token::Colon) {
234             let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
235             Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
236                 span: lo.to(self.prev_span),
237                 bound_generic_params: lifetime_defs,
238                 bounded_ty: ty,
239                 bounds,
240             }))
241         // FIXME: Decide what should be used here, `=` or `==`.
242         // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
243         } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
244             let rhs_ty = self.parse_ty()?;
245             Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
246                 span: lo.to(self.prev_span),
247                 lhs_ty: ty,
248                 rhs_ty,
249                 id: ast::DUMMY_NODE_ID,
250             }))
251         } else {
252             self.unexpected()
253         }
254     }
255
256     pub(super) fn choose_generics_over_qpath(&self) -> bool {
257         // There's an ambiguity between generic parameters and qualified paths in impls.
258         // If we see `<` it may start both, so we have to inspect some following tokens.
259         // The following combinations can only start generics,
260         // but not qualified paths (with one exception):
261         //     `<` `>` - empty generic parameters
262         //     `<` `#` - generic parameters with attributes
263         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
264         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
265         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
266         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
267         //     `<` const                - generic const parameter
268         // The only truly ambiguous case is
269         //     `<` IDENT `>` `::` IDENT ...
270         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
271         // because this is what almost always expected in practice, qualified paths in impls
272         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
273         self.token == token::Lt
274             && (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt)
275                 || self.look_ahead(1, |t| t.is_lifetime() || t.is_ident())
276                     && self.look_ahead(2, |t| {
277                         t == &token::Gt
278                             || t == &token::Comma
279                             || t == &token::Colon
280                             || t == &token::Eq
281                     })
282                 || self.is_keyword_ahead(1, &[kw::Const]))
283     }
284 }