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::bug;
51use rustc_span::def_id::LocalModId;
52use rustc_type_ir::TyKind::*;
53use tracing::instrument;
54
55use crate::query::Providers;
56use crate::ty::{
57 self, AdtDef, DefId, Ty, TyCtxt, TypeVisitableExt, TypingEnv, VariantDef, Visibility,
58};
59
60pub mod inhabited_predicate;
61
62pub use inhabited_predicate::InhabitedPredicate;
63
64pub(crate) fn provide(providers: &mut Providers) {
65 *providers = Providers {
66 inhabited_predicate_for_def,
67 inhabited_predicate_type,
68 is_opsem_inhabited_raw,
69 ..*providers
70 };
71}
72
73fn inhabited_predicate_for_def(tcx: TyCtxt<'_>, def_id: DefId) -> InhabitedPredicate<'_> {
76 match tcx.def_kind(def_id) {
77 DefKind::Enum => {
78 if let Some(def_id) = def_id.as_local() {
79 tcx.ensure_ok().check_representability(def_id);
80 }
81 let adt = tcx.adt_def(def_id);
82 InhabitedPredicate::any(tcx, adt.variants().iter().map(|v| v.inhabited_predicate(tcx)))
83 }
84 DefKind::Struct => {
85 if let Some(def_id) = def_id.as_local() {
86 tcx.ensure_ok().check_representability(def_id);
87 }
88 let adt = tcx.adt_def(def_id);
89 variant_inhabited_predicate(tcx, adt, adt.non_enum_variant())
90 }
91 DefKind::Variant => {
92 let adt = tcx.adt_def(tcx.parent(def_id));
93 let variant = adt.variant_with_id(def_id);
94 variant_inhabited_predicate(tcx, adt, variant)
95 }
96 def_kind => bug_impl(None, format_args!("unexpected DefKind: {0:?}", def_kind),
Location::caller())bug!("unexpected DefKind: {def_kind:?}"),
97 }
98}
99
100impl VariantDef {
101 pub fn inhabited_predicate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> InhabitedPredicate<'tcx> {
102 if self.fields.is_empty() {
103 return InhabitedPredicate::True;
104 }
105 tcx.inhabited_predicate_for_def(self.def_id)
106 }
107}
108
109fn variant_inhabited_predicate<'tcx>(
110 tcx: TyCtxt<'tcx>,
111 adt: AdtDef<'tcx>,
112 variant: &VariantDef,
113) -> InhabitedPredicate<'tcx> {
114 InhabitedPredicate::all(
115 tcx,
116 variant.fields.iter().map(|field| {
117 let pred = tcx
118 .type_of(field.did)
119 .instantiate_identity()
120 .skip_norm_wip()
121 .inhabited_predicate(tcx);
122 if adt.is_enum() {
123 return pred;
124 }
125 match field.vis {
126 Visibility::Public => pred,
127 Visibility::Restricted(from) => InhabitedPredicate::NotInModule(from).or(tcx, pred),
128 }
129 }),
130 )
131}
132
133impl<'tcx> Ty<'tcx> {
134 {}
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/ty/inhabitedness/mod.rs"),
::tracing_core::__macro_support::Option::Some(134u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/ty/inhabitedness/mod.rs:134",
"rustc_middle::ty::inhabitedness", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/ty/inhabitedness/mod.rs"),
::tracing_core::__macro_support::Option::Some(134u32),
::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)]
135 pub fn inhabited_predicate(self, tcx: TyCtxt<'tcx>) -> InhabitedPredicate<'tcx> {
136 debug_assert!(!self.has_infer());
137 match self.kind() {
138 Adt(adt, _) if adt.is_union() => InhabitedPredicate::True,
140 Adt(adt, _) if adt.variant_list_has_applicable_non_exhaustive() => {
142 InhabitedPredicate::True
143 }
144 Never => InhabitedPredicate::False,
145 Param(_)
147 | Alias(
148 _,
149 ty::AliasTy {
150 kind: ty::Inherent { .. } | ty::Projection { .. } | ty::Free { .. },
151 ..
152 },
153 ) => InhabitedPredicate::GenericType(self),
154 &Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
155 match def_id.as_local() {
156 None => InhabitedPredicate::True,
158 Some(local_def_id) => {
160 let key = ty::OpaqueTypeKey { def_id: local_def_id, args };
161 InhabitedPredicate::OpaqueType(key)
162 }
163 }
164 }
165 Tuple(tys) if tys.is_empty() => InhabitedPredicate::True,
166 Adt(..) | Array(..) | Tuple(_) => tcx.inhabited_predicate_type(self),
168 _ => InhabitedPredicate::True,
170 }
171 }
172
173 #[cfg_attr(bootstrap, doc = "#![feature(never_type)]")]
178 pub fn is_inhabited_from(
214 self,
215 tcx: TyCtxt<'tcx>,
216 module: LocalModId,
217 typing_env: ty::TypingEnv<'tcx>,
218 ) -> bool {
219 self.inhabited_predicate(tcx).apply(tcx, typing_env, module)
220 }
221
222 pub fn is_privately_uninhabited(
227 self,
228 tcx: TyCtxt<'tcx>,
229 typing_env: ty::TypingEnv<'tcx>,
230 ) -> bool {
231 !self.inhabited_predicate(tcx).apply_ignore_module(tcx, typing_env)
232 }
233
234 pub fn is_opsem_inhabited(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
243 OpsemInhabitedCtx { tcx, typing_env, seen: None, stop_at_ref: false }.is_inhabited_ty(self)
245 }
246}
247
248fn inhabited_predicate_type<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> InhabitedPredicate<'tcx> {
250 match *ty.kind() {
251 Adt(adt, args) => tcx.inhabited_predicate_for_def(adt.did()).instantiate(tcx, args),
252
253 Tuple(tys) => {
254 InhabitedPredicate::all(tcx, tys.iter().map(|ty| ty.inhabited_predicate(tcx)))
255 }
256
257 Array(ty, len) => match len.try_to_target_usize(tcx) {
260 Some(0) => InhabitedPredicate::True,
261 Some(1..) => ty.inhabited_predicate(tcx),
262 None => ty.inhabited_predicate(tcx).or(tcx, InhabitedPredicate::ConstIsZero(len)),
263 },
264
265 _ => bug_impl(None,
format_args!("unexpected TyKind, use `Ty::inhabited_predicate`"),
Location::caller())bug!("unexpected TyKind, use `Ty::inhabited_predicate`"),
266 }
267}
268
269struct OpsemInhabitedCtx<'tcx> {
272 tcx: TyCtxt<'tcx>,
273 typing_env: TypingEnv<'tcx>,
274 seen: Option<FxHashSet<DefId>>,
278 stop_at_ref: bool,
281}
282
283impl<'tcx> OpsemInhabitedCtx<'tcx> {
284 fn is_inhabited_ty(&mut self, ty: Ty<'tcx>) -> bool {
286 let tcx = self.tcx;
287 match *ty.kind() {
288 ty::Int(_)
290 | ty::Uint(_)
291 | ty::Float(_)
292 | ty::Bool
293 | ty::Char
294 | ty::Str
295 | ty::Foreign(..)
296 | ty::RawPtr(..)
297 | ty::FnPtr(..)
298 | ty::FnDef(..) => true,
299 ty::Dynamic(..) => true, ty::Slice(..) => true, ty::Never => false,
302
303 ty::Ref(_, pointee, _) => {
305 if self.stop_at_ref {
306 return true;
310 }
311 self.is_inhabited_ty(pointee)
312 }
313 ty::Tuple(tys) => tys.iter().all(|ty| self.is_inhabited_ty(ty)),
314 ty::Array(elem, len) => {
315 len.try_to_target_usize(tcx).unwrap() == 0 || self.is_inhabited_ty(elem)
316 }
317 ty::Pat(inner, _pat) => self.is_inhabited_ty(inner),
318 ty::Closure(_def, args) => {
319 let args = args.as_closure();
320 args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
321 }
322 ty::Coroutine(_def, args) => {
323 let args = args.as_coroutine();
324 args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
325 }
326 ty::CoroutineClosure(_def, args) => {
327 let args = args.as_coroutine_closure();
328 args.upvar_tys().iter().all(|ty| self.is_inhabited_ty(ty))
329 }
330 ty::UnsafeBinder(base) => {
331 let base = tcx.instantiate_bound_regions_with_erased((*base).into());
332 self.is_inhabited_ty(base)
333 }
334 ty::Adt(..) => self.is_inhabited_adt_ty(ty),
335
336 ty::Error(_error_guaranteed) => {
337 true
339 }
340
341 ty::Infer(..)
342 | ty::Placeholder(..)
343 | ty::Bound(..)
344 | ty::Param(..)
345 | ty::Alias(..)
346 | ty::CoroutineWitness(..) => {
347 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}`")
348 }
349 }
350 }
351
352 fn is_inhabited_adt_ty(&mut self, ty: Ty<'tcx>) -> bool {
353 let ty::Adt(adt_def, adt_args) = *ty.kind() else {
354 ::core::panicking::panic("internal error: entered unreachable code");unreachable! {}
355 };
356 let Self { tcx, typing_env, .. } = *self;
357
358 if adt_def.is_union() {
359 return true;
361 }
362
363 let Some(seen) = self.seen.as_mut() else {
364 return tcx.is_opsem_inhabited_raw(typing_env.as_query_input(ty));
366 };
367
368 let new_adt = seen.insert(adt_def.did());
369 let stop_at_ref_prev = self.stop_at_ref;
374 self.stop_at_ref |= !new_adt;
375
376 let inhabited = adt_def.variants().iter().any(|variant| {
378 variant.fields.iter().all(|field| {
379 let ty = field.ty(tcx, adt_args);
380 let ty = tcx.normalize_erasing_regions(typing_env, ty);
381 self.is_inhabited_ty(ty)
382 })
383 });
384
385 self.stop_at_ref = stop_at_ref_prev;
386 if new_adt {
388 self.seen.as_mut().unwrap().remove(&adt_def.did());
389 }
390
391 inhabited
392 }
393}
394
395fn is_opsem_inhabited_raw<'tcx>(
396 tcx: TyCtxt<'tcx>,
397 env: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
398) -> bool {
399 let (ty, typing_env) = (env.value, env.typing_env);
400 {
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!(
401 ty.kind(),
402 ty::Adt(..),
403 "the query should only be invoked by `Ty::is_opsem_inhabited`"
404 );
405
406 OpsemInhabitedCtx { tcx, typing_env, seen: Some(FxHashSet::default()), stop_at_ref: false }
407 .is_inhabited_adt_ty(ty)
408}