Skip to main content

rustc_middle/ty/inhabitedness/
mod.rs

1//! This module contains logic for determining whether a type is inhabited or
2//! uninhabited. The [`InhabitedPredicate`] type captures the minimum
3//! information needed to determine whether a type is inhabited given a
4//! `ParamEnv` and module ID.
5//!
6//! # Example
7//! ```rust
8//! mod a {
9//!     pub mod b {
10//!         pub struct SecretlyUninhabited {
11//!             _priv: !,
12//!         }
13//!     }
14//! }
15//!
16//! mod c {
17//!     enum Void {}
18//!     pub struct AlsoSecretlyUninhabited {
19//!         _priv: Void,
20//!     }
21//!     mod d {
22//!     }
23//! }
24//!
25//! struct Foo {
26//!     x: a::b::SecretlyUninhabited,
27//!     y: c::AlsoSecretlyUninhabited,
28//! }
29//! ```
30//! In this code, the type `Foo` will only be visibly uninhabited inside the
31//! modules `b`, `c` and `d`. Calling `inhabited_predicate` on `Foo` will
32//! return `NotInModule(b) AND NotInModule(c)`.
33//!
34//! We need this information for pattern-matching on `Foo` or types that contain
35//! `Foo`.
36//!
37//! # Example
38//! ```ignore(illustrative)
39//! let foo_result: Result<T, Foo> = ... ;
40//! let Ok(t) = foo_result;
41//! ```
42//! This code should only compile in modules where the uninhabitedness of `Foo`
43//! is visible.
44
45use rustc_data_structures::fx::FxHashSet;
46use rustc_hir::def::DefKind;
47use rustc_span::bug;
48use rustc_span::def_id::LocalModId;
49use rustc_type_ir::TyKind::*;
50use tracing::instrument;
51
52use crate::query::Providers;
53use crate::ty::{
54    self, AdtDef, DefId, Ty, TyCtxt, TypeVisitableExt, TypingEnv, VariantDef, Visibility,
55};
56
57pub mod inhabited_predicate;
58
59pub use inhabited_predicate::InhabitedPredicate;
60
61pub(crate) fn provide(providers: &mut Providers) {
62    *providers = Providers {
63        inhabited_predicate_for_def,
64        inhabited_predicate_type,
65        is_opsem_inhabited_adt_cached,
66        ..*providers
67    };
68}
69
70/// Returns an `InhabitedPredicate` that is generic over type parameters and
71/// requires calling [`InhabitedPredicate::instantiate`]
72fn inhabited_predicate_for_def(tcx: TyCtxt<'_>, def_id: DefId) -> InhabitedPredicate<'_> {
73    match tcx.def_kind(def_id) {
74        DefKind::Enum => {
75            if let Some(def_id) = def_id.as_local() {
76                tcx.ensure_ok().check_representability(def_id);
77            }
78            let adt = tcx.adt_def(def_id);
79            InhabitedPredicate::any(tcx, adt.variants().iter().map(|v| v.inhabited_predicate(tcx)))
80        }
81        DefKind::Struct => {
82            if let Some(def_id) = def_id.as_local() {
83                tcx.ensure_ok().check_representability(def_id);
84            }
85            let adt = tcx.adt_def(def_id);
86            variant_inhabited_predicate(tcx, adt, adt.non_enum_variant())
87        }
88        DefKind::Variant => {
89            let adt = tcx.adt_def(tcx.parent(def_id));
90            let variant = adt.variant_with_id(def_id);
91            variant_inhabited_predicate(tcx, adt, variant)
92        }
93        def_kind => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected DefKind: {0:?}", def_kind), Location::caller())bug!("unexpected DefKind: {def_kind:?}"),
94    }
95}
96
97impl VariantDef {
98    pub fn inhabited_predicate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> InhabitedPredicate<'tcx> {
99        if self.fields.is_empty() {
100            return InhabitedPredicate::True;
101        }
102        tcx.inhabited_predicate_for_def(self.def_id)
103    }
104}
105
106fn variant_inhabited_predicate<'tcx>(
107    tcx: TyCtxt<'tcx>,
108    adt: AdtDef<'tcx>,
109    variant: &VariantDef,
110) -> InhabitedPredicate<'tcx> {
111    InhabitedPredicate::all(
112        tcx,
113        variant.fields.iter().map(|field| {
114            let pred = tcx
115                .type_of(field.did)
116                .instantiate_identity()
117                .skip_norm_wip()
118                .inhabited_predicate(tcx);
119            if adt.is_enum() {
120                return pred;
121            }
122            match field.vis {
123                Visibility::Public => pred,
124                Visibility::Restricted(from) => InhabitedPredicate::NotInModule(from).or(tcx, pred),
125            }
126        }),
127    )
128}
129
130impl<'tcx> Ty<'tcx> {
131    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("inhabited_predicate",
                                "rustc_middle::ty::inhabitedness", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_middle/src/ty/inhabitedness/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(131u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::inhabitedness"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("self")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("self");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: InhabitedPredicate<'tcx> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if true {
                            if !!self.has_infer() {
                                ::core::panicking::panic("assertion failed: !self.has_infer()")
                            };
                        };
                        match self.kind() {
                            Adt(adt, _) if adt.is_union() => InhabitedPredicate::True,
                            Adt(adt, _) if
                                adt.variant_list_has_applicable_non_exhaustive() => {
                                InhabitedPredicate::True
                            }
                            Never => InhabitedPredicate::False,
                            Param(_) |
                                Alias(_, ty::AliasTy {
                                kind: ty::Inherent { .. } | ty::Projection { .. } |
                                    ty::Free { .. }, .. }) =>
                                InhabitedPredicate::GenericType(self),
                            &Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args,
                                .. }) => {
                                match def_id.as_local() {
                                    None => InhabitedPredicate::True,
                                    Some(local_def_id) => {
                                        let key = ty::OpaqueTypeKey { def_id: local_def_id, args };
                                        InhabitedPredicate::OpaqueType(key)
                                    }
                                }
                            }
                            Tuple(tys) if tys.is_empty() => InhabitedPredicate::True,
                            Adt(..) | Array(..) | Tuple(_) =>
                                tcx.inhabited_predicate_type(self),
                            _ => InhabitedPredicate::True,
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_middle/src/ty/inhabitedness/mod.rs:131",
                        "rustc_middle::ty::inhabitedness", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_middle/src/ty/inhabitedness/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(131u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::inhabitedness"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
132    pub fn inhabited_predicate(self, tcx: TyCtxt<'tcx>) -> InhabitedPredicate<'tcx> {
133        debug_assert!(!self.has_infer());
134        match self.kind() {
135            // For now, unions are always considered inhabited
136            Adt(adt, _) if adt.is_union() => InhabitedPredicate::True,
137            // Non-exhaustive ADTs from other crates are always considered inhabited
138            Adt(adt, _) if adt.variant_list_has_applicable_non_exhaustive() => {
139                InhabitedPredicate::True
140            }
141            Never => InhabitedPredicate::False,
142            // FIXME(#155345): This should only encounter rigid aliases with the new solver.
143            Param(_)
144            | Alias(
145                _,
146                ty::AliasTy {
147                    kind: ty::Inherent { .. } | ty::Projection { .. } | ty::Free { .. },
148                    ..
149                },
150            ) => InhabitedPredicate::GenericType(self),
151            &Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
152                match def_id.as_local() {
153                    // Foreign opaque is considered inhabited.
154                    None => InhabitedPredicate::True,
155                    // Local opaque type may possibly be revealed.
156                    Some(local_def_id) => {
157                        let key = ty::OpaqueTypeKey { def_id: local_def_id, args };
158                        InhabitedPredicate::OpaqueType(key)
159                    }
160                }
161            }
162            Tuple(tys) if tys.is_empty() => InhabitedPredicate::True,
163            // use a query for more complex cases
164            Adt(..) | Array(..) | Tuple(_) => tcx.inhabited_predicate_type(self),
165            // references and other types are inhabited
166            _ => InhabitedPredicate::True,
167        }
168    }
169
170    /// Checks whether a type is visibly uninhabited from a particular module.
171    ///
172    /// # Example
173    /// ```
174    /// # fn main() {}
175    /// enum Void {}
176    /// mod a {
177    ///     pub mod b {
178    ///         pub struct SecretlyUninhabited {
179    ///             _priv: !,
180    ///         }
181    ///     }
182    /// }
183    ///
184    /// mod c {
185    ///     use super::Void;
186    ///     pub struct AlsoSecretlyUninhabited {
187    ///         _priv: Void,
188    ///     }
189    ///     mod d {
190    ///     }
191    /// }
192    ///
193    /// struct Foo {
194    ///     x: a::b::SecretlyUninhabited,
195    ///     y: c::AlsoSecretlyUninhabited,
196    /// }
197    /// ```
198    /// In this code, the type `Foo` will only be visibly uninhabited inside the
199    /// modules b, c and d. This effects pattern-matching on `Foo` or types that
200    /// contain `Foo`.
201    ///
202    /// # Example
203    /// ```ignore (illustrative)
204    /// let foo_result: Result<T, Foo> = ... ;
205    /// let Ok(t) = foo_result;
206    /// ```
207    /// This code should only compile in modules where the uninhabitedness of Foo is
208    /// visible.
209    pub fn is_inhabited_from(
210        self,
211        tcx: TyCtxt<'tcx>,
212        module: LocalModId,
213        typing_env: ty::TypingEnv<'tcx>,
214    ) -> bool {
215        self.inhabited_predicate(tcx).apply(tcx, typing_env, module)
216    }
217
218    /// Returns true if the type is uninhabited without regard to visibility.
219    ///
220    /// This is still conservative; for instance, a `#[non_exhaustive]` enum *in another crate*
221    /// is always considered inhabited.
222    pub fn is_privately_uninhabited(
223        self,
224        tcx: TyCtxt<'tcx>,
225        typing_env: ty::TypingEnv<'tcx>,
226    ) -> bool {
227        !self.inhabited_predicate(tcx).apply_ignore_module(tcx, typing_env)
228    }
229
230    /// Returns whether `self` is considered inhabited on the opsem level, i.e., its validity
231    /// invariant might be satisfiable. `self` is expected to be monomorphic and normalized.
232    ///
233    /// Key constraints are:
234    /// - if a type's validity invariant is satisfiable, it must be opsem-inhabited.
235    /// - if a type's layout is marked uninhabited, it must be opsem-uninhabited.
236    ///
237    /// Beyond that, the value returned by this function is not a stable guarantee.
238    pub fn is_opsem_inhabited(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
239        // Handle simple cases directly, use the query with its cache for the rest.
240        OpsemInhabitedCtx { tcx, typing_env, seen: None, stop_at_ref: false }.is_inhabited_ty(self)
241    }
242}
243
244/// N.B. this query should only be called through `Ty::inhabited_predicate`
245fn inhabited_predicate_type<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> InhabitedPredicate<'tcx> {
246    match *ty.kind() {
247        Adt(adt, args) => tcx.inhabited_predicate_for_def(adt.did()).instantiate(tcx, args),
248
249        Tuple(tys) => {
250            InhabitedPredicate::all(tcx, tys.iter().map(|ty| ty.inhabited_predicate(tcx)))
251        }
252
253        // If we can evaluate the array length before having a `ParamEnv`, then
254        // we can simplify the predicate. This is an optimization.
255        Array(ty, len) => match len.try_to_target_usize(tcx) {
256            Some(0) => InhabitedPredicate::True,
257            Some(1..) => ty.inhabited_predicate(tcx),
258            None => ty.inhabited_predicate(tcx).or(tcx, InhabitedPredicate::ConstIsZero(len)),
259        },
260
261        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected TyKind, use `Ty::inhabited_predicate`"),
    Location::caller())bug!("unexpected TyKind, use `Ty::inhabited_predicate`"),
262    }
263}
264
265/// Context for computing whether a type is inhabited on the opsem level.
266/// See `is_opsem_inhabited` above for the spec of what we compute.
267struct OpsemInhabitedCtx<'tcx> {
268    tcx: TyCtxt<'tcx>,
269    typing_env: TypingEnv<'tcx>,
270    /// IDs of ADTs that have been encountered in the current stack.
271    /// It's `None` unless we are inside the `is_opsem_inhabited_adt_cached` query,
272    /// which is only invoked for more complex types.
273    seen: Option<FxHashSet<DefId>>,
274    /// If an ADT is encountered recursively within itself, then `stop_at_ref`
275    /// is set to `true`, and then any nested references are considered inhabited.
276    stop_at_ref: bool,
277}
278
279impl<'tcx> OpsemInhabitedCtx<'tcx> {
280    /// See `is_opsem_inhabited` above for the spec of what we compute.
281    fn is_inhabited_ty(&mut self, ty: Ty<'tcx>) -> bool {
282        let tcx = self.tcx;
283        match *ty.kind() {
284            // Trivially (un)inhabited types
285            ty::Int(_)
286            | ty::Uint(_)
287            | ty::Float(_)
288            | ty::Bool
289            | ty::Char
290            | ty::Str
291            | ty::Foreign(..)
292            | ty::RawPtr(..)
293            | ty::FnPtr(..)
294            | ty::FnDef(..) => true,
295            ty::Dynamic(..) => true, // We can't reason about traits, assume they are inhabited
296            ty::Slice(..) => true,   // Slices can always be empty
297            ty::Never => false,
298
299            // Types where we recurse
300            ty::Ref(_, pointee, _) => {
301                if self.stop_at_ref {
302                    // Bailing out here is safe as the layout code always considers references
303                    // inhabited, so the implication ("layout uninhabited => opsem uninhabited")
304                    // is upheld.
305                    return true;
306                }
307                self.is_inhabited_ty(pointee)
308            }
309            ty::Tuple(tys) => tys.iter().all(|ty| self.is_inhabited_ty(ty)),
310            ty::Array(elem, len) => {
311                len.try_to_target_usize(tcx).unwrap() == 0 || self.is_inhabited_ty(elem)
312            }
313            ty::Pat(inner, _pat) => self.is_inhabited_ty(inner),
314            ty::Closure(_def, args) => {
315                let args = args.as_closure();
316                args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
317            }
318            ty::Coroutine(_def, args) => {
319                let args = args.as_coroutine();
320                args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
321            }
322            ty::CoroutineClosure(_def, args) => {
323                let args = args.as_coroutine_closure();
324                args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
325            }
326            ty::UnsafeBinder(base) => {
327                let base = tcx.instantiate_bound_regions_with_erased((*base).into());
328                self.is_inhabited_ty(base)
329            }
330            ty::Adt(def, args) => self.is_inhabited_adt_ty(def, args),
331
332            ty::Error(_error_guaranteed) => {
333                // We have a token proving there was an error, so we can return a dummy value.
334                true
335            }
336
337            ty::Infer(..)
338            | ty::Placeholder(..)
339            | ty::Bound(..)
340            | ty::Param(..)
341            | ty::Alias(..)
342            | ty::CoroutineWitness(..) => {
343                ::rustc_span::macros::bug_impl(None,
    format_args!("non-normalized type in `is_opsem_uninhabited`: `{0}`", ty),
    Location::caller())bug!("non-normalized type in `is_opsem_uninhabited`: `{ty}`")
344            }
345        }
346    }
347
348    fn is_inhabited_adt_ty(
349        &mut self,
350        adt_def: ty::AdtDef<'tcx>,
351        adt_args: ty::GenericArgsRef<'tcx>,
352    ) -> bool {
353        let Self { tcx, typing_env, .. } = *self;
354
355        if adt_def.is_union() {
356            // Unions are always inhabited.
357            return true;
358        }
359
360        let Some(seen) = self.seen.as_mut() else {
361            // stop recursing, invoke the query.
362            return tcx
363                .is_opsem_inhabited_adt_cached(typing_env.as_query_input((adt_def, adt_args)));
364        };
365
366        let new_adt = seen.insert(adt_def.did());
367        // If we have seen this ADT before, stop at the next reference to avoid infinite
368        // recursion. We can't stop here since we have to ensure that "layout uninhabited"
369        // implies "opsem uninhabited". References are always layout-inhabited so the
370        // implication is vacuously true.
371        let stop_at_ref_prev = self.stop_at_ref;
372        self.stop_at_ref |= !new_adt;
373
374        // We are inhabited if in some variant all fields are inhabited.
375        let inhabited = adt_def.variants().iter().any(|variant| {
376            variant.fields.iter().all(|field| {
377                let ty = field.ty(tcx, adt_args);
378                let ty = tcx.normalize_erasing_regions(typing_env, ty);
379                self.is_inhabited_ty(ty)
380            })
381        });
382
383        self.stop_at_ref = stop_at_ref_prev;
384        // Remove the type again so that we allow it to appear on other branches.
385        if new_adt {
386            self.seen.as_mut().unwrap().remove(&adt_def.did());
387        }
388
389        inhabited
390    }
391}
392
393fn is_opsem_inhabited_adt_cached<'tcx>(
394    tcx: TyCtxt<'tcx>,
395    env: ty::PseudoCanonicalInput<'tcx, (ty::AdtDef<'tcx>, ty::GenericArgsRef<'tcx>)>,
396) -> bool {
397    let ((def, args), typing_env) = (env.value, env.typing_env);
398    OpsemInhabitedCtx { tcx, typing_env, seen: Some(FxHashSet::default()), stop_at_ref: false }
399        .is_inhabited_adt_ty(def, args)
400}