rustc_parse/parser/
generics.rs

1use rustc_ast::{
2    self as ast, AttrVec, DUMMY_NODE_ID, GenericBounds, GenericParam, GenericParamKind, TyKind,
3    WhereClause, token,
4};
5use rustc_errors::{Applicability, PResult};
6use rustc_span::{Ident, Span, kw, sym};
7use thin_vec::ThinVec;
8
9use super::{ForceCollect, Parser, Trailing, UsePreAttrPos};
10use crate::errors::{
11    self, MultipleWhereClauses, UnexpectedDefaultValueForLifetimeInGenericParameters,
12    UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody,
13    WhereClauseBeforeTupleStructBodySugg,
14};
15use crate::exp;
16
17enum PredicateKindOrStructBody {
18    PredicateKind(ast::WherePredicateKind),
19    StructBody(ThinVec<ast::FieldDef>),
20}
21
22impl<'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        // We might have a typo'd `Const` that was parsed as a type parameter.
45        if self.may_recover()
46            && ident.name.as_str().to_ascii_lowercase() == kw::Const.as_str()
47            && self.check_ident()
48        // `Const` followed by IDENT
49        {
50            return self.recover_const_param_with_mistyped_const(preceding_attrs, ident);
51        }
52
53        // Parse optional colon and param bounds.
54        let mut colon_span = None;
55        let bounds = if self.eat(exp!(Colon)) {
56            colon_span = Some(self.prev_token.span);
57            // recover from `impl Trait` in type param bound
58            if self.token.is_keyword(kw::Impl) {
59                let impl_span = self.token.span;
60                let snapshot = self.create_snapshot_for_diagnostic();
61                match self.parse_ty() {
62                    Ok(p) => {
63                        if let TyKind::ImplTrait(_, bounds) = &p.kind {
64                            let span = impl_span.to(self.token.span.shrink_to_lo());
65                            let mut err = self.dcx().struct_span_err(
66                                span,
67                                "expected trait bound, found `impl Trait` type",
68                            );
69                            err.span_label(span, "not a trait");
70                            if let [bound, ..] = &bounds[..] {
71                                err.span_suggestion_verbose(
72                                    impl_span.until(bound.span()),
73                                    "use the trait bounds directly",
74                                    String::new(),
75                                    Applicability::MachineApplicable,
76                                );
77                            }
78                            return Err(err);
79                        }
80                    }
81                    Err(err) => {
82                        err.cancel();
83                    }
84                }
85                self.restore_snapshot(snapshot);
86            }
87            self.parse_generic_bounds()?
88        } else {
89            Vec::new()
90        };
91
92        let default = if self.eat(exp!(Eq)) { Some(self.parse_ty()?) } else { None };
93        Ok(GenericParam {
94            ident,
95            id: ast::DUMMY_NODE_ID,
96            attrs: preceding_attrs,
97            bounds,
98            kind: GenericParamKind::Type { default },
99            is_placeholder: false,
100            colon_span,
101        })
102    }
103
104    pub(crate) fn parse_const_param(
105        &mut self,
106        preceding_attrs: AttrVec,
107    ) -> PResult<'a, GenericParam> {
108        let const_span = self.token.span;
109
110        self.expect_keyword(exp!(Const))?;
111        let ident = self.parse_ident()?;
112        self.expect(exp!(Colon))?;
113        let ty = self.parse_ty()?;
114
115        // Parse optional const generics default value.
116        let default = if self.eat(exp!(Eq)) { Some(self.parse_const_arg()?) } else { None };
117        let span = if let Some(ref default) = default {
118            const_span.to(default.value.span)
119        } else {
120            const_span.to(ty.span)
121        };
122
123        Ok(GenericParam {
124            ident,
125            id: ast::DUMMY_NODE_ID,
126            attrs: preceding_attrs,
127            bounds: Vec::new(),
128            kind: GenericParamKind::Const { ty, span, default },
129            is_placeholder: false,
130            colon_span: None,
131        })
132    }
133
134    pub(crate) fn recover_const_param_with_mistyped_const(
135        &mut self,
136        preceding_attrs: AttrVec,
137        mistyped_const_ident: Ident,
138    ) -> PResult<'a, GenericParam> {
139        let ident = self.parse_ident()?;
140        self.expect(exp!(Colon))?;
141        let ty = self.parse_ty()?;
142
143        // Parse optional const generics default value.
144        let default = if self.eat(exp!(Eq)) { Some(self.parse_const_arg()?) } else { None };
145        let span = if let Some(ref default) = default {
146            mistyped_const_ident.span.to(default.value.span)
147        } else {
148            mistyped_const_ident.span.to(ty.span)
149        };
150
151        self.dcx()
152            .struct_span_err(
153                mistyped_const_ident.span,
154                format!("`const` keyword was mistyped as `{}`", mistyped_const_ident.as_str()),
155            )
156            .with_span_suggestion_verbose(
157                mistyped_const_ident.span,
158                "use the `const` keyword",
159                kw::Const,
160                Applicability::MachineApplicable,
161            )
162            .emit();
163
164        Ok(GenericParam {
165            ident,
166            id: ast::DUMMY_NODE_ID,
167            attrs: preceding_attrs,
168            bounds: Vec::new(),
169            kind: GenericParamKind::Const { ty, span, default },
170            is_placeholder: false,
171            colon_span: None,
172        })
173    }
174
175    /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
176    /// a trailing comma and erroneous trailing attributes.
177    pub(super) fn parse_generic_params(&mut self) -> PResult<'a, ThinVec<ast::GenericParam>> {
178        let mut params = ThinVec::new();
179        let mut done = false;
180        while !done {
181            let attrs = self.parse_outer_attributes()?;
182            let param = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
183                if this.eat_keyword_noexpect(kw::SelfUpper) {
184                    // `Self` as a generic param is invalid. Here we emit the diagnostic and continue parsing
185                    // as if `Self` never existed.
186                    this.dcx()
187                        .emit_err(UnexpectedSelfInGenericParameters { span: this.prev_token.span });
188
189                    // Eat a trailing comma, if it exists.
190                    let _ = this.eat(exp!(Comma));
191                }
192
193                let param = if this.check_lifetime() {
194                    let lifetime = this.expect_lifetime();
195                    // Parse lifetime parameter.
196                    let (colon_span, bounds) = if this.eat(exp!(Colon)) {
197                        (Some(this.prev_token.span), this.parse_lt_param_bounds())
198                    } else {
199                        (None, Vec::new())
200                    };
201
202                    if this.check_noexpect(&token::Eq) && this.look_ahead(1, |t| t.is_lifetime()) {
203                        let lo = this.token.span;
204                        // Parse `= 'lifetime`.
205                        this.bump(); // `=`
206                        this.bump(); // `'lifetime`
207                        let span = lo.to(this.prev_token.span);
208                        this.dcx().emit_err(UnexpectedDefaultValueForLifetimeInGenericParameters {
209                            span,
210                        });
211                    }
212
213                    Some(ast::GenericParam {
214                        ident: lifetime.ident,
215                        id: lifetime.id,
216                        attrs,
217                        bounds,
218                        kind: ast::GenericParamKind::Lifetime,
219                        is_placeholder: false,
220                        colon_span,
221                    })
222                } else if this.check_keyword(exp!(Const)) {
223                    // Parse const parameter.
224                    Some(this.parse_const_param(attrs)?)
225                } else if this.check_ident() {
226                    // Parse type parameter.
227                    Some(this.parse_ty_param(attrs)?)
228                } else if this.token.can_begin_type() {
229                    // Trying to write an associated type bound? (#26271)
230                    let snapshot = this.create_snapshot_for_diagnostic();
231                    let lo = this.token.span;
232                    match this.parse_ty_where_predicate_kind() {
233                        Ok(_) => {
234                            this.dcx().emit_err(errors::BadAssocTypeBounds {
235                                span: lo.to(this.prev_token.span),
236                            });
237                            // FIXME - try to continue parsing other generics?
238                        }
239                        Err(err) => {
240                            err.cancel();
241                            // FIXME - maybe we should overwrite 'self' outside of `collect_tokens`?
242                            this.restore_snapshot(snapshot);
243                        }
244                    }
245                    return Ok((None, Trailing::No, UsePreAttrPos::No));
246                } else {
247                    // Check for trailing attributes and stop parsing.
248                    if !attrs.is_empty() {
249                        if !params.is_empty() {
250                            this.dcx().emit_err(errors::AttrAfterGeneric { span: attrs[0].span });
251                        } else {
252                            this.dcx()
253                                .emit_err(errors::AttrWithoutGenerics { span: attrs[0].span });
254                        }
255                    }
256                    return Ok((None, Trailing::No, UsePreAttrPos::No));
257                };
258
259                if !this.eat(exp!(Comma)) {
260                    done = true;
261                }
262                // We just ate the comma, so no need to capture the trailing token.
263                Ok((param, Trailing::No, UsePreAttrPos::No))
264            })?;
265
266            if let Some(param) = param {
267                params.push(param);
268            } else {
269                break;
270            }
271        }
272        Ok(params)
273    }
274
275    /// Parses a set of optional generic type parameter declarations. Where
276    /// clauses are not parsed here, and must be added later via
277    /// `parse_where_clause()`.
278    ///
279    /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
280    ///                  | ( < lifetimes , typaramseq ( , )? > )
281    /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
282    pub(super) fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
283        // invalid path separator `::` in function definition
284        // for example `fn invalid_path_separator::<T>() {}`
285        if self.eat_noexpect(&token::PathSep) {
286            self.dcx()
287                .emit_err(errors::InvalidPathSepInFnDefinition { span: self.prev_token.span });
288        }
289
290        let span_lo = self.token.span;
291        let (params, span) = if self.eat_lt() {
292            let params = self.parse_generic_params()?;
293            self.expect_gt_or_maybe_suggest_closing_generics(&params)?;
294            (params, span_lo.to(self.prev_token.span))
295        } else {
296            (ThinVec::new(), self.prev_token.span.shrink_to_hi())
297        };
298        Ok(ast::Generics {
299            params,
300            where_clause: WhereClause {
301                has_where_token: false,
302                predicates: ThinVec::new(),
303                span: self.prev_token.span.shrink_to_hi(),
304            },
305            span,
306        })
307    }
308
309    /// Parses an experimental fn contract
310    /// (`contract_requires(WWW) contract_ensures(ZZZ)`)
311    pub(super) fn parse_contract(
312        &mut self,
313    ) -> PResult<'a, Option<rustc_ast::ptr::P<ast::FnContract>>> {
314        let requires = if self.eat_keyword_noexpect(exp!(ContractRequires).kw) {
315            self.psess.gated_spans.gate(sym::contracts_internals, self.prev_token.span);
316            let precond = self.parse_expr()?;
317            Some(precond)
318        } else {
319            None
320        };
321        let ensures = if self.eat_keyword_noexpect(exp!(ContractEnsures).kw) {
322            self.psess.gated_spans.gate(sym::contracts_internals, self.prev_token.span);
323            let postcond = self.parse_expr()?;
324            Some(postcond)
325        } else {
326            None
327        };
328        if requires.is_none() && ensures.is_none() {
329            Ok(None)
330        } else {
331            Ok(Some(rustc_ast::ptr::P(ast::FnContract { requires, ensures })))
332        }
333    }
334
335    /// Parses an optional where-clause.
336    ///
337    /// ```ignore (only-for-syntax-highlight)
338    /// where T : Trait<U, V> + 'b, 'a : 'b
339    /// ```
340    pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
341        self.parse_where_clause_common(None).map(|(clause, _)| clause)
342    }
343
344    pub(super) fn parse_struct_where_clause(
345        &mut self,
346        struct_name: Ident,
347        body_insertion_point: Span,
348    ) -> PResult<'a, (WhereClause, Option<ThinVec<ast::FieldDef>>)> {
349        self.parse_where_clause_common(Some((struct_name, body_insertion_point)))
350    }
351
352    fn parse_where_clause_common(
353        &mut self,
354        struct_: Option<(Ident, Span)>,
355    ) -> PResult<'a, (WhereClause, Option<ThinVec<ast::FieldDef>>)> {
356        let mut where_clause = WhereClause {
357            has_where_token: false,
358            predicates: ThinVec::new(),
359            span: self.prev_token.span.shrink_to_hi(),
360        };
361        let mut tuple_struct_body = None;
362
363        if !self.eat_keyword(exp!(Where)) {
364            return Ok((where_clause, None));
365        }
366
367        if self.eat_noexpect(&token::Colon) {
368            let colon_span = self.prev_token.span;
369            self.dcx()
370                .struct_span_err(colon_span, "unexpected colon after `where`")
371                .with_span_suggestion_short(
372                    colon_span,
373                    "remove the colon",
374                    "",
375                    Applicability::MachineApplicable,
376                )
377                .emit();
378        }
379
380        where_clause.has_where_token = true;
381        let where_lo = self.prev_token.span;
382
383        // We are considering adding generics to the `where` keyword as an alternative higher-rank
384        // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
385        // change we parse those generics now, but report an error.
386        if self.choose_generics_over_qpath(0) {
387            let generics = self.parse_generics()?;
388            self.dcx().emit_err(errors::WhereOnGenerics { span: generics.span });
389        }
390
391        loop {
392            let where_sp = where_lo.to(self.prev_token.span);
393            let attrs = self.parse_outer_attributes()?;
394            let pred_lo = self.token.span;
395            let predicate = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
396                for attr in &attrs {
397                    self.psess.gated_spans.gate(sym::where_clause_attrs, attr.span);
398                }
399                let kind = if this.check_lifetime() && this.look_ahead(1, |t| !t.is_like_plus()) {
400                    let lifetime = this.expect_lifetime();
401                    // Bounds starting with a colon are mandatory, but possibly empty.
402                    this.expect(exp!(Colon))?;
403                    let bounds = this.parse_lt_param_bounds();
404                    Some(ast::WherePredicateKind::RegionPredicate(ast::WhereRegionPredicate {
405                        lifetime,
406                        bounds,
407                    }))
408                } else if this.check_type() {
409                    match this.parse_ty_where_predicate_kind_or_recover_tuple_struct_body(
410                        struct_, pred_lo, where_sp,
411                    )? {
412                        PredicateKindOrStructBody::PredicateKind(kind) => Some(kind),
413                        PredicateKindOrStructBody::StructBody(body) => {
414                            tuple_struct_body = Some(body);
415                            None
416                        }
417                    }
418                } else {
419                    None
420                };
421                let predicate = kind.map(|kind| ast::WherePredicate {
422                    attrs,
423                    kind,
424                    id: DUMMY_NODE_ID,
425                    span: pred_lo.to(this.prev_token.span),
426                    is_placeholder: false,
427                });
428                Ok((predicate, Trailing::No, UsePreAttrPos::No))
429            })?;
430            match predicate {
431                Some(predicate) => where_clause.predicates.push(predicate),
432                None => break,
433            }
434
435            let prev_token = self.prev_token.span;
436            let ate_comma = self.eat(exp!(Comma));
437
438            if self.eat_keyword_noexpect(kw::Where) {
439                self.dcx().emit_err(MultipleWhereClauses {
440                    span: self.token.span,
441                    previous: pred_lo,
442                    between: prev_token.shrink_to_hi().to(self.prev_token.span),
443                });
444            } else if !ate_comma {
445                break;
446            }
447        }
448
449        where_clause.span = where_lo.to(self.prev_token.span);
450        Ok((where_clause, tuple_struct_body))
451    }
452
453    fn parse_ty_where_predicate_kind_or_recover_tuple_struct_body(
454        &mut self,
455        struct_: Option<(Ident, Span)>,
456        pred_lo: Span,
457        where_sp: Span,
458    ) -> PResult<'a, PredicateKindOrStructBody> {
459        let mut snapshot = None;
460
461        if let Some(struct_) = struct_
462            && self.may_recover()
463            && self.token == token::OpenParen
464        {
465            snapshot = Some((struct_, self.create_snapshot_for_diagnostic()));
466        };
467
468        match self.parse_ty_where_predicate_kind() {
469            Ok(pred) => Ok(PredicateKindOrStructBody::PredicateKind(pred)),
470            Err(type_err) => {
471                let Some(((struct_name, body_insertion_point), mut snapshot)) = snapshot else {
472                    return Err(type_err);
473                };
474
475                // Check if we might have encountered an out of place tuple struct body.
476                match snapshot.parse_tuple_struct_body() {
477                    // Since we don't know the exact reason why we failed to parse the
478                    // predicate (we might have stumbled upon something bogus like `(T): ?`),
479                    // employ a simple heuristic to weed out some pathological cases:
480                    // Look for a semicolon (strong indicator) or anything that might mark
481                    // the end of the item (weak indicator) following the body.
482                    Ok(body)
483                        if matches!(snapshot.token.kind, token::Semi | token::Eof)
484                            || snapshot.token.can_begin_item() =>
485                    {
486                        type_err.cancel();
487
488                        let body_sp = pred_lo.to(snapshot.prev_token.span);
489                        let map = self.psess.source_map();
490
491                        self.dcx().emit_err(WhereClauseBeforeTupleStructBody {
492                            span: where_sp,
493                            name: struct_name.span,
494                            body: body_sp,
495                            sugg: map.span_to_snippet(body_sp).ok().map(|body| {
496                                WhereClauseBeforeTupleStructBodySugg {
497                                    left: body_insertion_point.shrink_to_hi(),
498                                    snippet: body,
499                                    right: map.end_point(where_sp).to(body_sp),
500                                }
501                            }),
502                        });
503
504                        self.restore_snapshot(snapshot);
505                        Ok(PredicateKindOrStructBody::StructBody(body))
506                    }
507                    Ok(_) => Err(type_err),
508                    Err(body_err) => {
509                        body_err.cancel();
510                        Err(type_err)
511                    }
512                }
513            }
514        }
515    }
516
517    fn parse_ty_where_predicate_kind(&mut self) -> PResult<'a, ast::WherePredicateKind> {
518        // Parse optional `for<'a, 'b>`.
519        // This `for` is parsed greedily and applies to the whole predicate,
520        // the bounded type can have its own `for` applying only to it.
521        // Examples:
522        // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
523        // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
524        // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
525        let (lifetime_defs, _) = self.parse_late_bound_lifetime_defs()?;
526
527        // Parse type with mandatory colon and (possibly empty) bounds,
528        // or with mandatory equality sign and the second type.
529        let ty = self.parse_ty_for_where_clause()?;
530        if self.eat(exp!(Colon)) {
531            let bounds = self.parse_generic_bounds()?;
532            Ok(ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
533                bound_generic_params: lifetime_defs,
534                bounded_ty: ty,
535                bounds,
536            }))
537        // FIXME: Decide what should be used here, `=` or `==`.
538        // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
539        } else if self.eat(exp!(Eq)) || self.eat(exp!(EqEq)) {
540            let rhs_ty = self.parse_ty()?;
541            Ok(ast::WherePredicateKind::EqPredicate(ast::WhereEqPredicate { lhs_ty: ty, rhs_ty }))
542        } else {
543            self.maybe_recover_bounds_doubled_colon(&ty)?;
544            self.unexpected_any()
545        }
546    }
547
548    pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
549        // There's an ambiguity between generic parameters and qualified paths in impls.
550        // If we see `<` it may start both, so we have to inspect some following tokens.
551        // The following combinations can only start generics,
552        // but not qualified paths (with one exception):
553        //     `<` `>` - empty generic parameters
554        //     `<` `#` - generic parameters with attributes
555        //     `<` (LIFETIME|IDENT) `>` - single generic parameter
556        //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
557        //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
558        //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
559        //     `<` const                - generic const parameter
560        //     `<` IDENT `?`            - RECOVERY for `impl<T ?Bound` missing a `:`, meant to
561        //                                avoid the `T?` to `Option<T>` recovery for types.
562        // The only truly ambiguous case is
563        //     `<` IDENT `>` `::` IDENT ...
564        // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
565        // because this is what almost always expected in practice, qualified paths in impls
566        // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
567        self.look_ahead(start, |t| t == &token::Lt)
568            && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
569                || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
570                    && self.look_ahead(start + 2, |t| {
571                        matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
572                        // Recovery-only branch -- this could be removed,
573                        // since it only affects diagnostics currently.
574                            || t.kind == token::Question
575                    })
576                || self.is_keyword_ahead(start + 1, &[kw::Const]))
577    }
578}