rustc_hir_analysis/collect/
generics_of.rs

1use std::assert_matches::assert_matches;
2use std::ops::ControlFlow;
3
4use hir::intravisit::{self, Visitor};
5use hir::{GenericParamKind, HirId, Node};
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::LocalDefId;
8use rustc_hir::intravisit::VisitorExt;
9use rustc_hir::{self as hir, AmbigArg};
10use rustc_middle::ty::{self, TyCtxt};
11use rustc_session::lint;
12use rustc_span::{Span, Symbol, kw};
13use tracing::{debug, instrument};
14
15use crate::delegation::inherit_generics_for_delegation_item;
16use crate::middle::resolve_bound_vars as rbv;
17
18#[instrument(level = "debug", skip(tcx), ret)]
19pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
20    use rustc_hir::*;
21
22    // For an RPITIT, synthesize generics which are equal to the opaque's generics
23    // and parent fn's generics compressed into one list.
24    if let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
25        tcx.opt_rpitit_info(def_id.to_def_id())
26    {
27        debug!("RPITIT fn_def_id={fn_def_id:?} opaque_def_id={opaque_def_id:?}");
28        let trait_def_id = tcx.parent(fn_def_id);
29        let opaque_ty_generics = tcx.generics_of(opaque_def_id);
30        let opaque_ty_parent_count = opaque_ty_generics.parent_count;
31        let mut own_params = opaque_ty_generics.own_params.clone();
32
33        let parent_generics = tcx.generics_of(trait_def_id);
34        let parent_count = parent_generics.parent_count + parent_generics.own_params.len();
35
36        let mut trait_fn_params = tcx.generics_of(fn_def_id).own_params.clone();
37
38        for param in &mut own_params {
39            param.index = param.index + parent_count as u32 + trait_fn_params.len() as u32
40                - opaque_ty_parent_count as u32;
41        }
42
43        trait_fn_params.extend(own_params);
44        own_params = trait_fn_params;
45
46        let param_def_id_to_index =
47            own_params.iter().map(|param| (param.def_id, param.index)).collect();
48
49        return ty::Generics {
50            parent: Some(trait_def_id),
51            parent_count,
52            own_params,
53            param_def_id_to_index,
54            has_self: opaque_ty_generics.has_self,
55            has_late_bound_regions: opaque_ty_generics.has_late_bound_regions,
56        };
57    }
58
59    let hir_id = tcx.local_def_id_to_hir_id(def_id);
60
61    let node = tcx.hir_node(hir_id);
62    if let Some(sig) = node.fn_sig()
63        && let Some(sig_id) = sig.decl.opt_delegation_sig_id()
64    {
65        return inherit_generics_for_delegation_item(tcx, def_id, sig_id);
66    }
67
68    let parent_def_id = match node {
69        Node::ImplItem(_)
70        | Node::TraitItem(_)
71        | Node::Variant(_)
72        | Node::Ctor(..)
73        | Node::Field(_) => {
74            let parent_id = tcx.hir_get_parent_item(hir_id);
75            Some(parent_id.to_def_id())
76        }
77        // FIXME(#43408) always enable this once `lazy_normalization` is
78        // stable enough and does not need a feature gate anymore.
79        Node::AnonConst(_) => {
80            let parent_did = tcx.parent(def_id.to_def_id());
81
82            // We don't do this unconditionally because the `DefId` parent of an anon const
83            // might be an implicitly created closure during `async fn` desugaring. This would
84            // have the wrong generics.
85            //
86            // i.e. `async fn foo<'a>() { let a = [(); { 1 + 2 }]; bar().await() }`
87            // would implicitly have a closure in its body that would be the parent of
88            // the `{ 1 + 2 }` anon const. This closure's generics is simply a witness
89            // instead of `['a]`.
90            let parent_did = if let DefKind::AnonConst = tcx.def_kind(parent_did) {
91                parent_did
92            } else {
93                tcx.hir_get_parent_item(hir_id).to_def_id()
94            };
95            debug!(?parent_did);
96
97            let mut in_param_ty = false;
98            for (_parent, node) in tcx.hir_parent_iter(hir_id) {
99                if let Some(generics) = node.generics() {
100                    let mut visitor = AnonConstInParamTyDetector { in_param_ty: false, ct: hir_id };
101
102                    in_param_ty = visitor.visit_generics(generics).is_break();
103                    break;
104                }
105            }
106
107            if in_param_ty {
108                // We do not allow generic parameters in anon consts if we are inside
109                // of a const parameter type, e.g. `struct Foo<const N: usize, const M: [u8; N]>` is not allowed.
110                None
111            } else if tcx.features().generic_const_exprs() {
112                let parent_node = tcx.parent_hir_node(hir_id);
113                debug!(?parent_node);
114                if let Node::Variant(Variant { disr_expr: Some(constant), .. }) = parent_node
115                    && constant.hir_id == hir_id
116                {
117                    // enum variant discriminants are not allowed to use any kind of generics
118                    None
119                } else if let Some(param_id) =
120                    tcx.hir().opt_const_param_default_param_def_id(hir_id)
121                {
122                    // If the def_id we are calling generics_of on is an anon ct default i.e:
123                    //
124                    // struct Foo<const N: usize = { .. }>;
125                    //        ^^^       ^          ^^^^^^ def id of this anon const
126                    //        ^         ^ param_id
127                    //        ^ parent_def_id
128                    //
129                    // then we only want to return generics for params to the left of `N`. If we don't do that we
130                    // end up with that const looking like: `ty::ConstKind::Unevaluated(def_id, args: [N#0])`.
131                    //
132                    // This causes ICEs (#86580) when building the args for Foo in `fn foo() -> Foo { .. }` as
133                    // we instantiate the defaults with the partially built args when we build the args. Instantiating
134                    // the `N#0` on the unevaluated const indexes into the empty args we're in the process of building.
135                    //
136                    // We fix this by having this function return the parent's generics ourselves and truncating the
137                    // generics to only include non-forward declared params (with the exception of the `Self` ty)
138                    //
139                    // For the above code example that means we want `args: []`
140                    // For the following struct def we want `args: [N#0]` when generics_of is called on
141                    // the def id of the `{ N + 1 }` anon const
142                    // struct Foo<const N: usize, const M: usize = { N + 1 }>;
143                    //
144                    // This has some implications for how we get the predicates available to the anon const
145                    // see `explicit_predicates_of` for more information on this
146                    let generics = tcx.generics_of(parent_did);
147                    let param_def_idx = generics.param_def_id_to_index[&param_id.to_def_id()];
148                    // In the above example this would be .params[..N#0]
149                    let own_params = generics.params_to(param_def_idx as usize, tcx).to_owned();
150                    let param_def_id_to_index =
151                        own_params.iter().map(|param| (param.def_id, param.index)).collect();
152
153                    return ty::Generics {
154                        // we set the parent of these generics to be our parent's parent so that we
155                        // dont end up with args: [N, M, N] for the const default on a struct like this:
156                        // struct Foo<const N: usize, const M: usize = { ... }>;
157                        parent: generics.parent,
158                        parent_count: generics.parent_count,
159                        own_params,
160                        param_def_id_to_index,
161                        has_self: generics.has_self,
162                        has_late_bound_regions: generics.has_late_bound_regions,
163                    };
164                } else {
165                    // HACK(eddyb) this provides the correct generics when
166                    // `feature(generic_const_expressions)` is enabled, so that const expressions
167                    // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
168                    //
169                    // Note that we do not supply the parent generics when using
170                    // `min_const_generics`.
171                    Some(parent_did)
172                }
173            } else {
174                let parent_node = tcx.parent_hir_node(hir_id);
175                let parent_node = match parent_node {
176                    Node::ConstArg(ca) => tcx.parent_hir_node(ca.hir_id),
177                    _ => parent_node,
178                };
179                match parent_node {
180                    // HACK(eddyb) this provides the correct generics for repeat
181                    // expressions' count (i.e. `N` in `[x; N]`), and explicit
182                    // `enum` discriminants (i.e. `D` in `enum Foo { Bar = D }`),
183                    // as they shouldn't be able to cause query cycle errors.
184                    Node::Expr(Expr { kind: ExprKind::Repeat(_, ct), .. })
185                        if ct.anon_const_hir_id() == Some(hir_id) =>
186                    {
187                        Some(parent_did)
188                    }
189                    Node::TyPat(_) => Some(parent_did),
190                    // Field default values inherit the ADT's generics.
191                    Node::Field(_) => Some(parent_did),
192                    _ => None,
193                }
194            }
195        }
196        Node::ConstBlock(_)
197        | Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
198            Some(tcx.typeck_root_def_id(def_id.to_def_id()))
199        }
200        Node::OpaqueTy(&hir::OpaqueTy {
201            origin:
202                hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, in_trait_or_impl }
203                | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
204            ..
205        }) => {
206            if in_trait_or_impl.is_some() {
207                assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn);
208            } else {
209                assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn);
210            }
211            Some(fn_def_id.to_def_id())
212        }
213        Node::OpaqueTy(&hir::OpaqueTy {
214            origin: hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty },
215            ..
216        }) => {
217            if in_assoc_ty {
218                assert_matches!(tcx.def_kind(parent), DefKind::AssocTy);
219            } else {
220                assert_matches!(tcx.def_kind(parent), DefKind::TyAlias);
221            }
222            debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent);
223            // Opaque types are always nested within another item, and
224            // inherit the generics of the item.
225            Some(parent.to_def_id())
226        }
227        _ => None,
228    };
229
230    enum Defaults {
231        Allowed,
232        // See #36887
233        FutureCompatDisallowed,
234        Deny,
235    }
236
237    let hir_generics = node.generics().unwrap_or(hir::Generics::empty());
238    let (opt_self, allow_defaults) = match node {
239        Node::Item(item) => {
240            match item.kind {
241                ItemKind::Trait(..) | ItemKind::TraitAlias(..) => {
242                    // Add in the self type parameter.
243                    //
244                    // Something of a hack: use the node id for the trait, also as
245                    // the node id for the Self type parameter.
246                    let opt_self = Some(ty::GenericParamDef {
247                        index: 0,
248                        name: kw::SelfUpper,
249                        def_id: def_id.to_def_id(),
250                        pure_wrt_drop: false,
251                        kind: ty::GenericParamDefKind::Type {
252                            has_default: false,
253                            synthetic: false,
254                        },
255                    });
256
257                    (opt_self, Defaults::Allowed)
258                }
259                ItemKind::TyAlias(..)
260                | ItemKind::Enum(..)
261                | ItemKind::Struct(..)
262                | ItemKind::Union(..) => (None, Defaults::Allowed),
263                ItemKind::Const(..) => (None, Defaults::Deny),
264                _ => (None, Defaults::FutureCompatDisallowed),
265            }
266        }
267
268        Node::OpaqueTy(..) => (None, Defaults::Allowed),
269
270        // GATs
271        Node::TraitItem(item) if matches!(item.kind, TraitItemKind::Type(..)) => {
272            (None, Defaults::Deny)
273        }
274        Node::ImplItem(item) if matches!(item.kind, ImplItemKind::Type(..)) => {
275            (None, Defaults::Deny)
276        }
277
278        _ => (None, Defaults::FutureCompatDisallowed),
279    };
280
281    let has_self = opt_self.is_some();
282    let mut parent_has_self = false;
283    let mut own_start = has_self as u32;
284    let parent_count = parent_def_id.map_or(0, |def_id| {
285        let generics = tcx.generics_of(def_id);
286        assert!(!has_self);
287        parent_has_self = generics.has_self;
288        own_start = generics.count() as u32;
289        generics.parent_count + generics.own_params.len()
290    });
291
292    let mut own_params: Vec<_> = Vec::with_capacity(hir_generics.params.len() + has_self as usize);
293
294    if let Some(opt_self) = opt_self {
295        own_params.push(opt_self);
296    }
297
298    let early_lifetimes = super::early_bound_lifetimes_from_generics(tcx, hir_generics);
299    own_params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
300        name: param.name.ident().name,
301        index: own_start + i as u32,
302        def_id: param.def_id.to_def_id(),
303        pure_wrt_drop: param.pure_wrt_drop,
304        kind: ty::GenericParamDefKind::Lifetime,
305    }));
306
307    // Now create the real type and const parameters.
308    let type_start = own_start - has_self as u32 + own_params.len() as u32;
309    let mut i: u32 = 0;
310    let mut next_index = || {
311        let prev = i;
312        i += 1;
313        prev + type_start
314    };
315
316    const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \
317    `struct`, `enum`, `type`, or `trait` definitions";
318
319    own_params.extend(hir_generics.params.iter().filter_map(|param| match param.kind {
320        GenericParamKind::Lifetime { .. } => None,
321        GenericParamKind::Type { default, synthetic, .. } => {
322            if default.is_some() {
323                match allow_defaults {
324                    Defaults::Allowed => {}
325                    Defaults::FutureCompatDisallowed => {
326                        tcx.node_span_lint(
327                            lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
328                            param.hir_id,
329                            param.span,
330                            |lint| {
331                                lint.primary_message(TYPE_DEFAULT_NOT_ALLOWED);
332                            },
333                        );
334                    }
335                    Defaults::Deny => {
336                        tcx.dcx().span_err(param.span, TYPE_DEFAULT_NOT_ALLOWED);
337                    }
338                }
339            }
340
341            let kind = ty::GenericParamDefKind::Type { has_default: default.is_some(), synthetic };
342
343            Some(ty::GenericParamDef {
344                index: next_index(),
345                name: param.name.ident().name,
346                def_id: param.def_id.to_def_id(),
347                pure_wrt_drop: param.pure_wrt_drop,
348                kind,
349            })
350        }
351        GenericParamKind::Const { ty: _, default, synthetic } => {
352            if !matches!(allow_defaults, Defaults::Allowed) && default.is_some() {
353                tcx.dcx().span_err(
354                    param.span,
355                    "defaults for const parameters are only allowed in \
356                    `struct`, `enum`, `type`, or `trait` definitions",
357                );
358            }
359
360            let index = next_index();
361
362            Some(ty::GenericParamDef {
363                index,
364                name: param.name.ident().name,
365                def_id: param.def_id.to_def_id(),
366                pure_wrt_drop: param.pure_wrt_drop,
367                kind: ty::GenericParamDefKind::Const { has_default: default.is_some(), synthetic },
368            })
369        }
370    }));
371
372    // provide junk type parameter defs - the only place that
373    // cares about anything but the length is instantiation,
374    // and we don't do that for closures.
375    if let Node::Expr(&hir::Expr {
376        kind: hir::ExprKind::Closure(hir::Closure { kind, .. }), ..
377    }) = node
378    {
379        // See `ClosureArgsParts`, `CoroutineArgsParts`, and `CoroutineClosureArgsParts`
380        // for info on the usage of each of these fields.
381        let dummy_args = match kind {
382            ClosureKind::Closure => &["<closure_kind>", "<closure_signature>", "<upvars>"][..],
383            ClosureKind::Coroutine(_) => &[
384                "<coroutine_kind>",
385                "<resume_ty>",
386                "<yield_ty>",
387                "<return_ty>",
388                "<witness>",
389                "<upvars>",
390            ][..],
391            ClosureKind::CoroutineClosure(_) => &[
392                "<closure_kind>",
393                "<closure_signature_parts>",
394                "<upvars>",
395                "<bound_captures_by_ref>",
396                "<witness>",
397            ][..],
398        };
399
400        own_params.extend(dummy_args.iter().map(|&arg| ty::GenericParamDef {
401            index: next_index(),
402            name: Symbol::intern(arg),
403            def_id: def_id.to_def_id(),
404            pure_wrt_drop: false,
405            kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
406        }));
407    }
408
409    // provide junk type parameter defs for const blocks.
410    if let Node::ConstBlock(_) = node {
411        own_params.push(ty::GenericParamDef {
412            index: next_index(),
413            name: rustc_span::sym::const_ty_placeholder,
414            def_id: def_id.to_def_id(),
415            pure_wrt_drop: false,
416            kind: ty::GenericParamDefKind::Type { has_default: false, synthetic: false },
417        });
418    }
419
420    if let Node::OpaqueTy(&hir::OpaqueTy { .. }) = node {
421        assert!(own_params.is_empty());
422
423        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
424        debug!(?lifetimes);
425
426        own_params.extend(lifetimes.iter().map(|&(_, param)| ty::GenericParamDef {
427            name: tcx.item_name(param.to_def_id()),
428            index: next_index(),
429            def_id: param.to_def_id(),
430            pure_wrt_drop: false,
431            kind: ty::GenericParamDefKind::Lifetime,
432        }))
433    }
434
435    let param_def_id_to_index =
436        own_params.iter().map(|param| (param.def_id, param.index)).collect();
437
438    ty::Generics {
439        parent: parent_def_id,
440        parent_count,
441        own_params,
442        param_def_id_to_index,
443        has_self: has_self || parent_has_self,
444        has_late_bound_regions: has_late_bound_regions(tcx, node),
445    }
446}
447
448fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<Span> {
449    struct LateBoundRegionsDetector<'tcx> {
450        tcx: TyCtxt<'tcx>,
451        outer_index: ty::DebruijnIndex,
452    }
453
454    impl<'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'tcx> {
455        type Result = ControlFlow<Span>;
456        fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx, AmbigArg>) -> ControlFlow<Span> {
457            match ty.kind {
458                hir::TyKind::BareFn(..) => {
459                    self.outer_index.shift_in(1);
460                    let res = intravisit::walk_ty(self, ty);
461                    self.outer_index.shift_out(1);
462                    res
463                }
464                hir::TyKind::UnsafeBinder(_) => {
465                    self.outer_index.shift_in(1);
466                    let res = intravisit::walk_ty(self, ty);
467                    self.outer_index.shift_out(1);
468                    res
469                }
470                _ => intravisit::walk_ty(self, ty),
471            }
472        }
473
474        fn visit_poly_trait_ref(&mut self, tr: &'tcx hir::PolyTraitRef<'tcx>) -> ControlFlow<Span> {
475            self.outer_index.shift_in(1);
476            let res = intravisit::walk_poly_trait_ref(self, tr);
477            self.outer_index.shift_out(1);
478            res
479        }
480
481        fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) -> ControlFlow<Span> {
482            match self.tcx.named_bound_var(lt.hir_id) {
483                Some(rbv::ResolvedArg::StaticLifetime | rbv::ResolvedArg::EarlyBound(..)) => {
484                    ControlFlow::Continue(())
485                }
486                Some(rbv::ResolvedArg::LateBound(debruijn, _, _))
487                    if debruijn < self.outer_index =>
488                {
489                    ControlFlow::Continue(())
490                }
491                Some(
492                    rbv::ResolvedArg::LateBound(..)
493                    | rbv::ResolvedArg::Free(..)
494                    | rbv::ResolvedArg::Error(_),
495                )
496                | None => ControlFlow::Break(lt.ident.span),
497            }
498        }
499    }
500
501    fn has_late_bound_regions<'tcx>(
502        tcx: TyCtxt<'tcx>,
503        generics: &'tcx hir::Generics<'tcx>,
504        decl: &'tcx hir::FnDecl<'tcx>,
505    ) -> Option<Span> {
506        let mut visitor = LateBoundRegionsDetector { tcx, outer_index: ty::INNERMOST };
507        for param in generics.params {
508            if let GenericParamKind::Lifetime { .. } = param.kind {
509                if tcx.is_late_bound(param.hir_id) {
510                    return Some(param.span);
511                }
512            }
513        }
514        visitor.visit_fn_decl(decl).break_value()
515    }
516
517    let decl = node.fn_decl()?;
518    let generics = node.generics()?;
519    has_late_bound_regions(tcx, generics, decl)
520}
521
522struct AnonConstInParamTyDetector {
523    in_param_ty: bool,
524    ct: HirId,
525}
526
527impl<'v> Visitor<'v> for AnonConstInParamTyDetector {
528    type Result = ControlFlow<()>;
529
530    fn visit_generic_param(&mut self, p: &'v hir::GenericParam<'v>) -> Self::Result {
531        if let GenericParamKind::Const { ty, default: _, synthetic: _ } = p.kind {
532            let prev = self.in_param_ty;
533            self.in_param_ty = true;
534            let res = self.visit_ty_unambig(ty);
535            self.in_param_ty = prev;
536            res
537        } else {
538            ControlFlow::Continue(())
539        }
540    }
541
542    fn visit_anon_const(&mut self, c: &'v hir::AnonConst) -> Self::Result {
543        if self.in_param_ty && self.ct == c.hir_id {
544            return ControlFlow::Break(());
545        }
546        intravisit::walk_anon_const(self, c)
547    }
548}