rustc_middle/ty/inhabitedness/
mod.rs1use 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
70fn 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 Adt(adt, _) if adt.is_union() => InhabitedPredicate::True,
137 Adt(adt, _) if adt.variant_list_has_applicable_non_exhaustive() => {
139 InhabitedPredicate::True
140 }
141 Never => InhabitedPredicate::False,
142 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 None => InhabitedPredicate::True,
155 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 Adt(..) | Array(..) | Tuple(_) => tcx.inhabited_predicate_type(self),
165 _ => InhabitedPredicate::True,
167 }
168 }
169
170 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 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 pub fn is_opsem_inhabited(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
239 OpsemInhabitedCtx { tcx, typing_env, seen: None, stop_at_ref: false }.is_inhabited_ty(self)
241 }
242}
243
244fn 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 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
265struct OpsemInhabitedCtx<'tcx> {
268 tcx: TyCtxt<'tcx>,
269 typing_env: TypingEnv<'tcx>,
270 seen: Option<FxHashSet<DefId>>,
274 stop_at_ref: bool,
277}
278
279impl<'tcx> OpsemInhabitedCtx<'tcx> {
280 fn is_inhabited_ty(&mut self, ty: Ty<'tcx>) -> bool {
282 let tcx = self.tcx;
283 match *ty.kind() {
284 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, ty::Slice(..) => true, ty::Never => false,
298
299 ty::Ref(_, pointee, _) => {
301 if self.stop_at_ref {
302 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 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 return true;
358 }
359
360 let Some(seen) = self.seen.as_mut() else {
361 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 let stop_at_ref_prev = self.stop_at_ref;
372 self.stop_at_ref |= !new_adt;
373
374 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 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}