rustc_middle/ty/inhabitedness/
mod.rs1#![cfg_attr(bootstrap, doc = "#![feature(never_type)]")]
9use 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
72fn 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 Adt(adt, _) if adt.is_union() => InhabitedPredicate::True,
139 Adt(adt, _) if adt.variant_list_has_applicable_non_exhaustive() => {
141 InhabitedPredicate::True
142 }
143 Never => InhabitedPredicate::False,
144 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 None => InhabitedPredicate::True,
157 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 Adt(..) | Array(..) | Tuple(_) => tcx.inhabited_predicate_type(self),
167 _ => InhabitedPredicate::True,
169 }
170 }
171
172 #[cfg_attr(bootstrap, doc = "#![feature(never_type)]")]
177 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 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 pub fn is_opsem_inhabited(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
242 OpsemInhabitedCtx { tcx, typing_env, seen: None, stop_at_ref: false }.is_inhabited_ty(self)
244 }
245}
246
247fn 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 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
268struct OpsemInhabitedCtx<'tcx> {
271 tcx: TyCtxt<'tcx>,
272 typing_env: TypingEnv<'tcx>,
273 seen: Option<FxHashSet<DefId>>,
277 stop_at_ref: bool,
280}
281
282impl<'tcx> OpsemInhabitedCtx<'tcx> {
283 fn is_inhabited_ty(&mut self, ty: Ty<'tcx>) -> bool {
285 let tcx = self.tcx;
286 match *ty.kind() {
287 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, ty::Slice(..) => true, ty::Never => false,
301
302 ty::Ref(_, pointee, _) => {
304 if self.stop_at_ref {
305 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 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 return true;
360 }
361
362 let Some(seen) = self.seen.as_mut() else {
363 return tcx.is_opsem_inhabited_raw(typing_env.as_query_input(ty));
365 };
366
367 let new_adt = seen.insert(adt_def.did());
368 let stop_at_ref_prev = self.stop_at_ref;
373 self.stop_at_ref |= !new_adt;
374
375 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 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}