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#![cfg_attr(bootstrap, doc = "#![feature(never_type)]")]
9//! mod a {
10//!     pub mod b {
11//!         pub struct SecretlyUninhabited {
12//!             _priv: !,
13//!         }
14//!     }
15//! }
16//!
17//! mod c {
18//!     enum Void {}
19//!     pub struct AlsoSecretlyUninhabited {
20//!         _priv: Void,
21//!     }
22//!     mod d {
23//!     }
24//! }
25//!
26//! struct Foo {
27//!     x: a::b::SecretlyUninhabited,
28//!     y: c::AlsoSecretlyUninhabited,
29//! }
30//! ```
31//! In this code, the type `Foo` will only be visibly uninhabited inside the
32//! modules `b`, `c` and `d`. Calling `inhabited_predicate` on `Foo` will
33//! return `NotInModule(b) AND NotInModule(c)`.
34//!
35//! We need this information for pattern-matching on `Foo` or types that contain
36//! `Foo`.
37//!
38//! # Example
39//! ```ignore(illustrative)
40//! let foo_result: Result<T, Foo> = ... ;
41//! let Ok(t) = foo_result;
42//! ```
43//! This code should only compile in modules where the uninhabitedness of `Foo`
44//! is visible.
45
46use std::assert_matches;
47
48use rustc_data_structures::fx::FxHashSet;
49use rustc_hir::def::DefKind;
50use rustc_span::def_id::LocalModId;
51use rustc_type_ir::TyKind::*;
52use tracing::instrument;
53
54use crate::query::Providers;
55use crate::ty::{
56    self, AdtDef, DefId, Ty, TyCtxt, TypeVisitableExt, TypingEnv, VariantDef, Visibility,
57};
58
59pub mod inhabited_predicate;
60
61pub use inhabited_predicate::InhabitedPredicate;
62
63pub(crate) fn provide(providers: &mut Providers) {
64    *providers = Providers {
65        inhabited_predicate_for_def,
66        inhabited_predicate_type,
67        is_opsem_inhabited_raw,
68        ..*providers
69    };
70}
71
72/// Returns an `InhabitedPredicate` that is generic over type parameters and
73/// requires calling [`InhabitedPredicate::instantiate`]
74fn inhabited_predicate_for_def(tcx: TyCtxt<'_>, def_id: DefId) -> InhabitedPredicate<'_> {
75    match tcx.def_kind(def_id) {
76        DefKind::Enum => {
77            if let Some(def_id) = def_id.as_local() {
78                tcx.ensure_ok().check_representability(def_id);
79            }
80            let adt = tcx.adt_def(def_id);
81            InhabitedPredicate::any(tcx, adt.variants().iter().map(|v| v.inhabited_predicate(tcx)))
82        }
83        DefKind::Struct => {
84            if let Some(def_id) = def_id.as_local() {
85                tcx.ensure_ok().check_representability(def_id);
86            }
87            let adt = tcx.adt_def(def_id);
88            variant_inhabited_predicate(tcx, adt, adt.non_enum_variant())
89        }
90        DefKind::Variant => {
91            let adt = tcx.adt_def(tcx.parent(def_id));
92            let variant = adt.variant_with_id(def_id);
93            variant_inhabited_predicate(tcx, adt, variant)
94        }
95        def_kind => crate::util::bug::bug_fmt(format_args!("unexpected DefKind: {0:?}", def_kind))bug!("unexpected DefKind: {def_kind:?}"),
96    }
97}
98
99impl VariantDef {
100    pub fn inhabited_predicate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> InhabitedPredicate<'tcx> {
101        if self.fields.is_empty() {
102            return InhabitedPredicate::True;
103        }
104        tcx.inhabited_predicate_for_def(self.def_id)
105    }
106}
107
108fn variant_inhabited_predicate<'tcx>(
109    tcx: TyCtxt<'tcx>,
110    adt: AdtDef<'tcx>,
111    variant: &VariantDef,
112) -> InhabitedPredicate<'tcx> {
113    InhabitedPredicate::all(
114        tcx,
115        variant.fields.iter().map(|field| {
116            let pred = tcx
117                .type_of(field.did)
118                .instantiate_identity()
119                .skip_norm_wip()
120                .inhabited_predicate(tcx);
121            if adt.is_enum() {
122                return pred;
123            }
124            match field.vis {
125                Visibility::Public => pred,
126                Visibility::Restricted(from) => InhabitedPredicate::NotInModule(from).or(tcx, pred),
127            }
128        }),
129    )
130}
131
132impl<'tcx> Ty<'tcx> {
133    {}
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/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_middle/src/ty/inhabitedness/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(133u32),
                                ::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/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_middle/src/ty/inhabitedness/mod.rs:133",
                        "rustc_middle::ty::inhabitedness", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_middle/src/ty/inhabitedness/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(133u32),
                        ::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)]
134    pub fn inhabited_predicate(self, tcx: TyCtxt<'tcx>) -> InhabitedPredicate<'tcx> {
135        debug_assert!(!self.has_infer());
136        match self.kind() {
137            // For now, unions are always considered inhabited
138            Adt(adt, _) if adt.is_union() => InhabitedPredicate::True,
139            // Non-exhaustive ADTs from other crates are always considered inhabited
140            Adt(adt, _) if adt.variant_list_has_applicable_non_exhaustive() => {
141                InhabitedPredicate::True
142            }
143            Never => InhabitedPredicate::False,
144            // FIXME(#155345): This should only encounter rigid aliases with the new solver.
145            Param(_)
146            | Alias(
147                _,
148                ty::AliasTy {
149                    kind: ty::Inherent { .. } | ty::Projection { .. } | ty::Free { .. },
150                    ..
151                },
152            ) => InhabitedPredicate::GenericType(self),
153            &Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
154                match def_id.as_local() {
155                    // Foreign opaque is considered inhabited.
156                    None => InhabitedPredicate::True,
157                    // Local opaque type may possibly be revealed.
158                    Some(local_def_id) => {
159                        let key = ty::OpaqueTypeKey { def_id: local_def_id, args };
160                        InhabitedPredicate::OpaqueType(key)
161                    }
162                }
163            }
164            Tuple(tys) if tys.is_empty() => InhabitedPredicate::True,
165            // use a query for more complex cases
166            Adt(..) | Array(..) | Tuple(_) => tcx.inhabited_predicate_type(self),
167            // references and other types are inhabited
168            _ => InhabitedPredicate::True,
169        }
170    }
171
172    /// Checks whether a type is visibly uninhabited from a particular module.
173    ///
174    /// # Example
175    /// ```
176    #[cfg_attr(bootstrap, doc = "#![feature(never_type)]")]
177    /// # fn main() {}
178    /// enum Void {}
179    /// mod a {
180    ///     pub mod b {
181    ///         pub struct SecretlyUninhabited {
182    ///             _priv: !,
183    ///         }
184    ///     }
185    /// }
186    ///
187    /// mod c {
188    ///     use super::Void;
189    ///     pub struct AlsoSecretlyUninhabited {
190    ///         _priv: Void,
191    ///     }
192    ///     mod d {
193    ///     }
194    /// }
195    ///
196    /// struct Foo {
197    ///     x: a::b::SecretlyUninhabited,
198    ///     y: c::AlsoSecretlyUninhabited,
199    /// }
200    /// ```
201    /// In this code, the type `Foo` will only be visibly uninhabited inside the
202    /// modules b, c and d. This effects pattern-matching on `Foo` or types that
203    /// contain `Foo`.
204    ///
205    /// # Example
206    /// ```ignore (illustrative)
207    /// let foo_result: Result<T, Foo> = ... ;
208    /// let Ok(t) = foo_result;
209    /// ```
210    /// This code should only compile in modules where the uninhabitedness of Foo is
211    /// visible.
212    pub fn is_inhabited_from(
213        self,
214        tcx: TyCtxt<'tcx>,
215        module: LocalModId,
216        typing_env: ty::TypingEnv<'tcx>,
217    ) -> bool {
218        self.inhabited_predicate(tcx).apply(tcx, typing_env, module)
219    }
220
221    /// Returns true if the type is uninhabited without regard to visibility.
222    ///
223    /// This is still conservative; for instance, a `#[non_exhaustive]` enum *in another crate*
224    /// is always considered inhabited.
225    pub fn is_privately_uninhabited(
226        self,
227        tcx: TyCtxt<'tcx>,
228        typing_env: ty::TypingEnv<'tcx>,
229    ) -> bool {
230        !self.inhabited_predicate(tcx).apply_ignore_module(tcx, typing_env)
231    }
232
233    /// Returns whether `self` is considered inhabited on the opsem level, i.e., its validity
234    /// invariant might be satisfiable. `self` is expected to be monomorphic and normalized.
235    ///
236    /// Key constraints are:
237    /// - if a type's validity invariant is satisfiable, it must be opsem-inhabited.
238    /// - if a type's layout is marked uninhabited, it must be opsem-uninhabited.
239    ///
240    /// Beyond that, the value returned by this function is not a stable guarantee.
241    pub fn is_opsem_inhabited(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
242        // Handle simple cases directly, use the query with its cache for the rest.
243        OpsemInhabitedCtx { tcx, typing_env, seen: None, stop_at_ref: false }.is_inhabited_ty(self)
244    }
245}
246
247/// N.B. this query should only be called through `Ty::inhabited_predicate`
248fn inhabited_predicate_type<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> InhabitedPredicate<'tcx> {
249    match *ty.kind() {
250        Adt(adt, args) => tcx.inhabited_predicate_for_def(adt.did()).instantiate(tcx, args),
251
252        Tuple(tys) => {
253            InhabitedPredicate::all(tcx, tys.iter().map(|ty| ty.inhabited_predicate(tcx)))
254        }
255
256        // If we can evaluate the array length before having a `ParamEnv`, then
257        // we can simplify the predicate. This is an optimization.
258        Array(ty, len) => match len.try_to_target_usize(tcx) {
259            Some(0) => InhabitedPredicate::True,
260            Some(1..) => ty.inhabited_predicate(tcx),
261            None => ty.inhabited_predicate(tcx).or(tcx, InhabitedPredicate::ConstIsZero(len)),
262        },
263
264        _ => crate::util::bug::bug_fmt(format_args!("unexpected TyKind, use `Ty::inhabited_predicate`"))bug!("unexpected TyKind, use `Ty::inhabited_predicate`"),
265    }
266}
267
268/// Context for computing whether a type is inhabited on the opsem level.
269/// See `is_opsem_inhabited` above for the spec of what we compute.
270struct OpsemInhabitedCtx<'tcx> {
271    tcx: TyCtxt<'tcx>,
272    typing_env: TypingEnv<'tcx>,
273    /// IDs of ADTs that have been encountered in the current stack.
274    /// It's `None` unless we are inside the `is_opsem_inhabited_raw` query,
275    /// which is only invoked for more complex types.
276    seen: Option<FxHashSet<DefId>>,
277    /// If an ADT is encountered recursively within itself, then `stop_at_ref`
278    /// is set to `true`, and then any nested references are considered inhabited.
279    stop_at_ref: bool,
280}
281
282impl<'tcx> OpsemInhabitedCtx<'tcx> {
283    /// See `is_opsem_inhabited` above for the spec of what we compute.
284    fn is_inhabited_ty(&mut self, ty: Ty<'tcx>) -> bool {
285        let tcx = self.tcx;
286        match *ty.kind() {
287            // Trivially (un)inhabited types
288            ty::Int(_)
289            | ty::Uint(_)
290            | ty::Float(_)
291            | ty::Bool
292            | ty::Char
293            | ty::Str
294            | ty::Foreign(..)
295            | ty::RawPtr(..)
296            | ty::FnPtr(..)
297            | ty::FnDef(..) => true,
298            ty::Dynamic(..) => true, // We can't reason about traits, assume they are inhabited
299            ty::Slice(..) => true,   // Slices can always be empty
300            ty::Never => false,
301
302            // Types where we recurse
303            ty::Ref(_, pointee, _) => {
304                if self.stop_at_ref {
305                    // Bailing out here is safe as the layout code always considers references
306                    // inhabited, so the implication ("layout uninhabited => opsem uninhabited")
307                    // is upheld.
308                    return true;
309                }
310                self.is_inhabited_ty(pointee)
311            }
312            ty::Tuple(tys) => tys.iter().all(|ty| self.is_inhabited_ty(ty)),
313            ty::Array(elem, len) => {
314                len.try_to_target_usize(tcx).unwrap() == 0 || self.is_inhabited_ty(elem)
315            }
316            ty::Pat(inner, _pat) => self.is_inhabited_ty(inner),
317            ty::Closure(_def, args) => {
318                let args = args.as_closure();
319                args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
320            }
321            ty::Coroutine(_def, args) => {
322                let args = args.as_coroutine();
323                args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
324            }
325            ty::CoroutineClosure(_def, args) => {
326                let args = args.as_coroutine_closure();
327                args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
328            }
329            ty::UnsafeBinder(base) => {
330                let base = tcx.instantiate_bound_regions_with_erased((*base).into());
331                self.is_inhabited_ty(base)
332            }
333            ty::Adt(..) => self.is_inhabited_adt_ty(ty),
334
335            ty::Error(_error_guaranteed) => {
336                // We have a token proving there was an error, so we can return a dummy value.
337                true
338            }
339
340            ty::Infer(..)
341            | ty::Placeholder(..)
342            | ty::Bound(..)
343            | ty::Param(..)
344            | ty::Alias(..)
345            | ty::CoroutineWitness(..) => {
346                crate::util::bug::bug_fmt(format_args!("non-normalized type in `is_opsem_uninhabited`: `{0}`",
        ty))bug!("non-normalized type in `is_opsem_uninhabited`: `{ty}`")
347            }
348        }
349    }
350
351    fn is_inhabited_adt_ty(&mut self, ty: Ty<'tcx>) -> bool {
352        let ty::Adt(adt_def, adt_args) = *ty.kind() else {
353            ::core::panicking::panic("internal error: entered unreachable code");unreachable! {}
354        };
355        let Self { tcx, typing_env, .. } = *self;
356
357        if adt_def.is_union() {
358            // Unions are always inhabited.
359            return true;
360        }
361
362        let Some(seen) = self.seen.as_mut() else {
363            // stop recursing, invoke the query.
364            return tcx.is_opsem_inhabited_raw(typing_env.as_query_input(ty));
365        };
366
367        let new_adt = seen.insert(adt_def.did());
368        // If we have seen this ADT before, stop at the next reference to avoid infinite
369        // recursion. We can't stop here since we have to ensure that "layout uninhabited"
370        // implies "opsem uninhabited". References are always layout-inhabited so the
371        // implication is vacuously true.
372        let stop_at_ref_prev = self.stop_at_ref;
373        self.stop_at_ref |= !new_adt;
374
375        // We are inhabited if in some variant all fields are inhabited.
376        let inhabited = adt_def.variants().iter().any(|variant| {
377            variant.fields.iter().all(|field| {
378                let ty = field.ty(tcx, adt_args);
379                let ty = tcx.normalize_erasing_regions(typing_env, ty);
380                self.is_inhabited_ty(ty)
381            })
382        });
383
384        self.stop_at_ref = stop_at_ref_prev;
385        // Remove the type again so that we allow it to appear on other branches.
386        if new_adt {
387            self.seen.as_mut().unwrap().remove(&adt_def.did());
388        }
389
390        inhabited
391    }
392}
393
394fn is_opsem_inhabited_raw<'tcx>(
395    tcx: TyCtxt<'tcx>,
396    env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
397) -> bool {
398    let (ty, typing_env) = (env.value, env.typing_env);
399    {
    match ty.kind() {
        ty::Adt(..) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val, "ty::Adt(..)",
                ::core::option::Option::Some(format_args!("the query should only be invoked by `Ty::is_opsem_inhabited`")));
        }
    }
};assert_matches!(
400        ty.kind(),
401        ty::Adt(..),
402        "the query should only be invoked by `Ty::is_opsem_inhabited`"
403    );
404
405    OpsemInhabitedCtx { tcx, typing_env, seen: Some(FxHashSet::default()), stop_at_ref: false }
406        .is_inhabited_adt_ty(ty)
407}