]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/generics.rs
Merge branch 'master' into feature/incorporate-tracing
[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     /// ```text
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_token.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 const_span = 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::min_const_generics, const_span.to(self.prev_token.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, kw_span: const_span },
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                         *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_token.span))
154         } else {
155             (vec![], self.prev_token.span.shrink_to_hi())
156         };
157         Ok(ast::Generics {
158             params,
159             where_clause: WhereClause {
160                 has_where_token: false,
161                 predicates: Vec::new(),
162                 span: self.prev_token.span.shrink_to_hi(),
163             },
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 = WhereClause {
175             has_where_token: false,
176             predicates: Vec::new(),
177             span: self.prev_token.span.shrink_to_hi(),
178         };
179
180         if !self.eat_keyword(kw::Where) {
181             return Ok(where_clause);
182         }
183         where_clause.has_where_token = true;
184         let lo = self.prev_token.span;
185
186         // We are considering adding generics to the `where` keyword as an alternative higher-rank
187         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
188         // change we parse those generics now, but report an error.
189         if self.choose_generics_over_qpath(0) {
190             let generics = self.parse_generics()?;
191             self.struct_span_err(
192                 generics.span,
193                 "generic parameters on `where` clauses are reserved for future use",
194             )
195             .span_label(generics.span, "currently unsupported")
196             .emit();
197         }
198
199         loop {
200             let lo = self.token.span;
201             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
202                 let lifetime = self.expect_lifetime();
203                 // Bounds starting with a colon are mandatory, but possibly empty.
204                 self.expect(&token::Colon)?;
205                 let bounds = self.parse_lt_param_bounds();
206                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
207                     ast::WhereRegionPredicate {
208                         span: lo.to(self.prev_token.span),
209                         lifetime,
210                         bounds,
211                     },
212                 ));
213             } else if self.check_type() {
214                 where_clause.predicates.push(self.parse_ty_where_predicate()?);
215             } else {
216                 break;
217             }
218
219             if !self.eat(&token::Comma) {
220                 break;
221             }
222         }
223
224         where_clause.span = lo.to(self.prev_token.span);
225         Ok(where_clause)
226     }
227
228     fn parse_ty_where_predicate(&mut self) -> PResult<'a, ast::WherePredicate> {
229         let lo = self.token.span;
230         // Parse optional `for<'a, 'b>`.
231         // This `for` is parsed greedily and applies to the whole predicate,
232         // the bounded type can have its own `for` applying only to it.
233         // Examples:
234         // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
235         // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
236         // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
237         let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
238
239         // Parse type with mandatory colon and (possibly empty) bounds,
240         // or with mandatory equality sign and the second type.
241         let ty = self.parse_ty()?;
242         if self.eat(&token::Colon) {
243             let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?;
244             Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
245                 span: lo.to(self.prev_token.span),
246                 bound_generic_params: lifetime_defs,
247                 bounded_ty: ty,
248                 bounds,
249             }))
250         // FIXME: Decide what should be used here, `=` or `==`.
251         // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
252         } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
253             let rhs_ty = self.parse_ty()?;
254             Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
255                 span: lo.to(self.prev_token.span),
256                 lhs_ty: ty,
257                 rhs_ty,
258                 id: ast::DUMMY_NODE_ID,
259             }))
260         } else {
261             self.unexpected()
262         }
263     }
264
265     pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
266         // There's an ambiguity between generic parameters and qualified paths in impls.
267         // If we see `<` it may start both, so we have to inspect some following tokens.
268         // The following combinations can only start generics,
269         // but not qualified paths (with one exception):
270         //     `<` `>` - empty generic parameters
271         //     `<` `#` - generic parameters with attributes
272         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
273         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
274         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
275         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
276         //     `<` const                - generic const parameter
277         // The only truly ambiguous case is
278         //     `<` IDENT `>` `::` IDENT ...
279         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
280         // because this is what almost always expected in practice, qualified paths in impls
281         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
282         self.look_ahead(start, |t| t == &token::Lt)
283             && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
284                 || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
285                     && self.look_ahead(start + 2, |t| {
286                         matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
287                     })
288                 || self.is_keyword_ahead(start + 1, &[kw::Const]))
289     }
290 }