Skip to main content

rustc_hir_analysis/collect/
generics_of.rs

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