]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/generics.rs
Rollup merge of #69546 - matthiaskrgr:slice_to_vec, r=davidtwco,nagisa
[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(attrs[0].span, "attribute without generic parameters")
125                             .span_label(
126                                 attrs[0].span,
127                                 "attributes are only permitted when preceding parameters",
128                             )
129                             .emit();
130                     }
131                 }
132                 break;
133             }
134
135             if !self.eat(&token::Comma) {
136                 break;
137             }
138         }
139         Ok(params)
140     }
141
142     /// Parses a set of optional generic type parameter declarations. Where
143     /// clauses are not parsed here, and must be added later via
144     /// `parse_where_clause()`.
145     ///
146     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
147     ///                  | ( < lifetimes , typaramseq ( , )? > )
148     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
149     pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
150         let span_lo = self.token.span;
151         let (params, span) = if self.eat_lt() {
152             let params = self.parse_generic_params()?;
153             self.expect_gt()?;
154             (params, span_lo.to(self.prev_span))
155         } else {
156             (vec![], self.prev_span.shrink_to_hi())
157         };
158         Ok(ast::Generics {
159             params,
160             where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP },
161             span,
162         })
163     }
164
165     /// Parses an optional where-clause and places it in `generics`.
166     ///
167     /// ```ignore (only-for-syntax-highlight)
168     /// where T : Trait<U, V> + 'b, 'a : 'b
169     /// ```
170     pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
171         let mut where_clause =
172             WhereClause { predicates: Vec::new(), span: self.prev_span.shrink_to_hi() };
173
174         if !self.eat_keyword(kw::Where) {
175             return Ok(where_clause);
176         }
177         let lo = self.prev_span;
178
179         // We are considering adding generics to the `where` keyword as an alternative higher-rank
180         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
181         // change we parse those generics now, but report an error.
182         if self.choose_generics_over_qpath() {
183             let generics = self.parse_generics()?;
184             self.struct_span_err(
185                 generics.span,
186                 "generic parameters on `where` clauses are reserved for future use",
187             )
188             .span_label(generics.span, "currently unsupported")
189             .emit();
190         }
191
192         loop {
193             let lo = self.token.span;
194             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
195                 let lifetime = self.expect_lifetime();
196                 // Bounds starting with a colon are mandatory, but possibly empty.
197                 self.expect(&token::Colon)?;
198                 let bounds = self.parse_lt_param_bounds();
199                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
200                     ast::WhereRegionPredicate { span: lo.to(self.prev_span), lifetime, bounds },
201                 ));
202             } else if self.check_type() {
203                 where_clause.predicates.push(self.parse_ty_where_predicate()?);
204             } else {
205                 break;
206             }
207
208             if !self.eat(&token::Comma) {
209                 break;
210             }
211         }
212
213         where_clause.span = lo.to(self.prev_span);
214         Ok(where_clause)
215     }
216
217     fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
218         let lo = self.token.span;
219         // Parse optional `for<'a, 'b>`.
220         // This `for` is parsed greedily and applies to the whole predicate,
221         // the bounded type can have its own `for` applying only to it.
222         // Examples:
223         // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
224         // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
225         // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
226         let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
227
228         // Parse type with mandatory colon and (possibly empty) bounds,
229         // or with mandatory equality sign and the second type.
230         let ty = self.parse_ty()?;
231         if self.eat(&token::Colon) {
232             let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
233             Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
234                 span: lo.to(self.prev_span),
235                 bound_generic_params: lifetime_defs,
236                 bounded_ty: ty,
237                 bounds,
238             }))
239         // FIXME: Decide what should be used here, `=` or `==`.
240         // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
241         } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
242             let rhs_ty = self.parse_ty()?;
243             Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
244                 span: lo.to(self.prev_span),
245                 lhs_ty: ty,
246                 rhs_ty,
247                 id: ast::DUMMY_NODE_ID,
248             }))
249         } else {
250             self.unexpected()
251         }
252     }
253
254     pub(super) fn choose_generics_over_qpath(&self) -> bool {
255         // There's an ambiguity between generic parameters and qualified paths in impls.
256         // If we see `<` it may start both, so we have to inspect some following tokens.
257         // The following combinations can only start generics,
258         // but not qualified paths (with one exception):
259         //     `<` `>` - empty generic parameters
260         //     `<` `#` - generic parameters with attributes
261         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
262         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
263         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
264         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
265         //     `<` const                - generic const parameter
266         // The only truly ambiguous case is
267         //     `<` IDENT `>` `::` IDENT ...
268         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
269         // because this is what almost always expected in practice, qualified paths in impls
270         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
271         self.token == token::Lt
272             && (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt)
273                 || self.look_ahead(1, |t| t.is_lifetime() || t.is_ident())
274                     && self.look_ahead(2, |t| {
275                         t == &token::Gt
276                             || t == &token::Comma
277                             || t == &token::Colon
278                             || t == &token::Eq
279                     })
280                 || self.is_keyword_ahead(1, &[kw::Const]))
281     }
282 }