rustc_type_ir/
opaque_ty.rs

1use derive_where::derive_where;
2#[cfg(feature = "nightly")]
3use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext};
4use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic};
5
6use crate::inherent::*;
7use crate::{self as ty, Interner};
8
9#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)]
10#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
11#[cfg_attr(
12    feature = "nightly",
13    derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
14)]
15pub struct OpaqueTypeKey<I: Interner> {
16    pub def_id: I::LocalDefId,
17    pub args: I::GenericArgs,
18}
19
20impl<I: Interner> OpaqueTypeKey<I> {
21    pub fn iter_captured_args(self, cx: I) -> impl Iterator<Item = (usize, I::GenericArg)> {
22        let variances = cx.variances_of(self.def_id.into());
23        std::iter::zip(self.args.iter(), variances.iter()).enumerate().filter_map(
24            |(i, (arg, v))| match (arg.kind(), v) {
25                (_, ty::Invariant) => Some((i, arg)),
26                (ty::GenericArgKind::Lifetime(_), ty::Bivariant) => None,
27                _ => panic!("unexpected opaque type arg variance"),
28            },
29        )
30    }
31
32    pub fn fold_captured_lifetime_args(
33        self,
34        cx: I,
35        mut f: impl FnMut(I::Region) -> I::Region,
36    ) -> Self {
37        let Self { def_id, args } = self;
38        let variances = cx.variances_of(def_id.into());
39        let args =
40            std::iter::zip(args.iter(), variances.iter()).map(|(arg, v)| match (arg.kind(), v) {
41                (ty::GenericArgKind::Lifetime(_), ty::Bivariant) => arg,
42                (ty::GenericArgKind::Lifetime(lt), _) => f(lt).into(),
43                _ => arg,
44            });
45        let args = cx.mk_args_from_iter(args);
46        Self { def_id, args }
47    }
48}