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(&mut self) -> PResult<'a, Option<Box<ast::FnContract>>> {
312        let requires = if self.eat_keyword_noexpect(exp!(ContractRequires).kw) {
313            self.psess.gated_spans.gate(sym::contracts_internals, self.prev_token.span);
314            let precond = self.parse_expr()?;
315            Some(precond)
316        } else {
317            None
318        };
319        let ensures = if self.eat_keyword_noexpect(exp!(ContractEnsures).kw) {
320            self.psess.gated_spans.gate(sym::contracts_internals, self.prev_token.span);
321            let postcond = self.parse_expr()?;
322            Some(postcond)
323        } else {
324            None
325        };
326        if requires.is_none() && ensures.is_none() {
327            Ok(None)
328        } else {
329            Ok(Some(Box::new(ast::FnContract { requires, ensures })))
330        }
331    }
332
333    /// Parses an optional where-clause.
334    ///
335    /// ```ignore (only-for-syntax-highlight)
336    /// where T : Trait<U, V> + 'b, 'a : 'b
337    /// ```
338    pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
339        self.parse_where_clause_common(None).map(|(clause, _)| clause)
340    }
341
342    pub(super) fn parse_struct_where_clause(
343        &mut self,
344        struct_name: Ident,
345        body_insertion_point: Span,
346    ) -> PResult<'a, (WhereClause, Option<ThinVec<ast::FieldDef>>)> {
347        self.parse_where_clause_common(Some((struct_name, body_insertion_point)))
348    }
349
350    fn parse_where_clause_common(
351        &mut self,
352        struct_: Option<(Ident, Span)>,
353    ) -> PResult<'a, (WhereClause, Option<ThinVec<ast::FieldDef>>)> {
354        let mut where_clause = WhereClause {
355            has_where_token: false,
356            predicates: ThinVec::new(),
357            span: self.prev_token.span.shrink_to_hi(),
358        };
359        let mut tuple_struct_body = None;
360
361        if !self.eat_keyword(exp!(Where)) {
362            return Ok((where_clause, None));
363        }
364
365        if self.eat_noexpect(&token::Colon) {
366            let colon_span = self.prev_token.span;
367            self.dcx()
368                .struct_span_err(colon_span, "unexpected colon after `where`")
369                .with_span_suggestion_short(
370                    colon_span,
371                    "remove the colon",
372                    "",
373                    Applicability::MachineApplicable,
374                )
375                .emit();
376        }
377
378        where_clause.has_where_token = true;
379        let where_lo = self.prev_token.span;
380
381        // We are considering adding generics to the `where` keyword as an alternative higher-rank
382        // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
383        // change we parse those generics now, but report an error.
384        if self.choose_generics_over_qpath(0) {
385            let generics = self.parse_generics()?;
386            self.dcx().emit_err(errors::WhereOnGenerics { span: generics.span });
387        }
388
389        loop {
390            let where_sp = where_lo.to(self.prev_token.span);
391            let attrs = self.parse_outer_attributes()?;
392            let pred_lo = self.token.span;
393            let predicate = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
394                for attr in &attrs {
395                    self.psess.gated_spans.gate(sym::where_clause_attrs, attr.span);
396                }
397                let kind = if this.check_lifetime() && this.look_ahead(1, |t| !t.is_like_plus()) {
398                    let lifetime = this.expect_lifetime();
399                    // Bounds starting with a colon are mandatory, but possibly empty.
400                    this.expect(exp!(Colon))?;
401                    let bounds = this.parse_lt_param_bounds();
402                    Some(ast::WherePredicateKind::RegionPredicate(ast::WhereRegionPredicate {
403                        lifetime,
404                        bounds,
405                    }))
406                } else if this.check_type() {
407                    match this.parse_ty_where_predicate_kind_or_recover_tuple_struct_body(
408                        struct_, pred_lo, where_sp,
409                    )? {
410                        PredicateKindOrStructBody::PredicateKind(kind) => Some(kind),
411                        PredicateKindOrStructBody::StructBody(body) => {
412                            tuple_struct_body = Some(body);
413                            None
414                        }
415                    }
416                } else {
417                    None
418                };
419                let predicate = kind.map(|kind| ast::WherePredicate {
420                    attrs,
421                    kind,
422                    id: DUMMY_NODE_ID,
423                    span: pred_lo.to(this.prev_token.span),
424                    is_placeholder: false,
425                });
426                Ok((predicate, Trailing::No, UsePreAttrPos::No))
427            })?;
428            match predicate {
429                Some(predicate) => where_clause.predicates.push(predicate),
430                None => break,
431            }
432
433            let prev_token = self.prev_token.span;
434            let ate_comma = self.eat(exp!(Comma));
435
436            if self.eat_keyword_noexpect(kw::Where) {
437                self.dcx().emit_err(MultipleWhereClauses {
438                    span: self.token.span,
439                    previous: pred_lo,
440                    between: prev_token.shrink_to_hi().to(self.prev_token.span),
441                });
442            } else if !ate_comma {
443                break;
444            }
445        }
446
447        where_clause.span = where_lo.to(self.prev_token.span);
448        Ok((where_clause, tuple_struct_body))
449    }
450
451    fn parse_ty_where_predicate_kind_or_recover_tuple_struct_body(
452        &mut self,
453        struct_: Option<(Ident, Span)>,
454        pred_lo: Span,
455        where_sp: Span,
456    ) -> PResult<'a, PredicateKindOrStructBody> {
457        let mut snapshot = None;
458
459        if let Some(struct_) = struct_
460            && self.may_recover()
461            && self.token == token::OpenParen
462        {
463            snapshot = Some((struct_, self.create_snapshot_for_diagnostic()));
464        };
465
466        match self.parse_ty_where_predicate_kind() {
467            Ok(pred) => Ok(PredicateKindOrStructBody::PredicateKind(pred)),
468            Err(type_err) => {
469                let Some(((struct_name, body_insertion_point), mut snapshot)) = snapshot else {
470                    return Err(type_err);
471                };
472
473                // Check if we might have encountered an out of place tuple struct body.
474                match snapshot.parse_tuple_struct_body() {
475                    // Since we don't know the exact reason why we failed to parse the
476                    // predicate (we might have stumbled upon something bogus like `(T): ?`),
477                    // employ a simple heuristic to weed out some pathological cases:
478                    // Look for a semicolon (strong indicator) or anything that might mark
479                    // the end of the item (weak indicator) following the body.
480                    Ok(body)
481                        if matches!(snapshot.token.kind, token::Semi | token::Eof)
482                            || snapshot.token.can_begin_item() =>
483                    {
484                        type_err.cancel();
485
486                        let body_sp = pred_lo.to(snapshot.prev_token.span);
487                        let map = self.psess.source_map();
488
489                        self.dcx().emit_err(WhereClauseBeforeTupleStructBody {
490                            span: where_sp,
491                            name: struct_name.span,
492                            body: body_sp,
493                            sugg: map.span_to_snippet(body_sp).ok().map(|body| {
494                                WhereClauseBeforeTupleStructBodySugg {
495                                    left: body_insertion_point.shrink_to_hi(),
496                                    snippet: body,
497                                    right: map.end_point(where_sp).to(body_sp),
498                                }
499                            }),
500                        });
501
502                        self.restore_snapshot(snapshot);
503                        Ok(PredicateKindOrStructBody::StructBody(body))
504                    }
505                    Ok(_) => Err(type_err),
506                    Err(body_err) => {
507                        body_err.cancel();
508                        Err(type_err)
509                    }
510                }
511            }
512        }
513    }
514
515    fn parse_ty_where_predicate_kind(&mut self) -> PResult<'a, ast::WherePredicateKind> {
516        // Parse optional `for<'a, 'b>`.
517        // This `for` is parsed greedily and applies to the whole predicate,
518        // the bounded type can have its own `for` applying only to it.
519        // Examples:
520        // * `for<'a> Trait1<'a>: Trait2<'a /* ok */>`
521        // * `(for<'a> Trait1<'a>): Trait2<'a /* not ok */>`
522        // * `for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /* ok */, 'b /* not ok */>`
523        let (lifetime_defs, _) = self.parse_late_bound_lifetime_defs()?;
524
525        // Parse type with mandatory colon and (possibly empty) bounds,
526        // or with mandatory equality sign and the second type.
527        let ty = self.parse_ty_for_where_clause()?;
528        if self.eat(exp!(Colon)) {
529            let bounds = self.parse_generic_bounds()?;
530            Ok(ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
531                bound_generic_params: lifetime_defs,
532                bounded_ty: ty,
533                bounds,
534            }))
535        // FIXME: Decide what should be used here, `=` or `==`.
536        // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
537        } else if self.eat(exp!(Eq)) || self.eat(exp!(EqEq)) {
538            let rhs_ty = self.parse_ty()?;
539            Ok(ast::WherePredicateKind::EqPredicate(ast::WhereEqPredicate { lhs_ty: ty, rhs_ty }))
540        } else {
541            self.maybe_recover_bounds_doubled_colon(&ty)?;
542            self.unexpected_any()
543        }
544    }
545
546    pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool {
547        // There's an ambiguity between generic parameters and qualified paths in impls.
548        // If we see `<` it may start both, so we have to inspect some following tokens.
549        // The following combinations can only start generics,
550        // but not qualified paths (with one exception):
551        //     `<` `>` - empty generic parameters
552        //     `<` `#` - generic parameters with attributes
553        //     `<` (LIFETIME|IDENT) `>` - single generic parameter
554        //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
555        //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
556        //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
557        //     `<` const                - generic const parameter
558        //     `<` IDENT `?`            - RECOVERY for `impl<T ?Bound` missing a `:`, meant to
559        //                                avoid the `T?` to `Option<T>` recovery for types.
560        // The only truly ambiguous case is
561        //     `<` IDENT `>` `::` IDENT ...
562        // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
563        // because this is what almost always expected in practice, qualified paths in impls
564        // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
565        self.look_ahead(start, |t| t == &token::Lt)
566            && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt)
567                || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident())
568                    && self.look_ahead(start + 2, |t| {
569                        matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq)
570                        // Recovery-only branch -- this could be removed,
571                        // since it only affects diagnostics currently.
572                            || t.kind == token::Question
573                    })
574                || self.is_keyword_ahead(start + 1, &[kw::Const]))
575    }
576}