rust/compiler/rustc_ty_utils/src/needs_drop.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

384 lines
15 KiB
Rust
Raw Normal View History

//! Check whether a type has (potentially) non-trivial drop glue.
2020-03-29 10:19:48 -05:00
use rustc_data_structures::fx::FxHashSet;
use rustc_hir::def_id::DefId;
use rustc_middle::query::Providers;
2020-03-29 09:41:09 -05:00
use rustc_middle::ty::util::{needs_drop_components, AlwaysRequiresDrop};
use rustc_middle::ty::GenericArgsRef;
2022-05-08 00:17:58 -05:00
use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt};
use rustc_session::Limit;
use rustc_span::{sym, DUMMY_SP};
use crate::errors::NeedsDropOverflow;
type NeedsDropResult<T> = Result<T, AlwaysRequiresDrop>;
2021-09-02 06:04:29 -05:00
fn needs_drop_raw<'tcx>(tcx: TyCtxt<'tcx>, query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool {
// If we don't know a type doesn't need drop, for example if it's a type
// parameter without a `Copy` bound, then we conservatively return that it
// needs drop.
let adt_has_dtor =
|adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
let res = drop_tys_helper(tcx, query.value, query.param_env, adt_has_dtor, false)
.filter(filter_array_elements(tcx, query.param_env))
.next()
.is_some();
2021-09-01 06:06:15 -05:00
debug!("needs_drop_raw({:?}) = {:?}", query, res);
res
}
/// HACK: in order to not mistakenly assume that `[PhantomData<T>; N]` requires drop glue
/// we check the element type for drop glue. The correct fix would be looking at the
/// entirety of the code around `needs_drop_components` and this file and come up with
/// logic that is easier to follow while not repeating any checks that may thus diverge.
fn filter_array_elements<'tcx>(
tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> impl Fn(&Result<Ty<'tcx>, AlwaysRequiresDrop>) -> bool {
move |ty| match ty {
Ok(ty) => match *ty.kind() {
ty::Array(elem, _) => tcx.needs_drop_raw(param_env.and(elem)),
_ => true,
},
Err(AlwaysRequiresDrop) => true,
}
}
fn has_significant_drop_raw<'tcx>(
tcx: TyCtxt<'tcx>,
query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
) -> bool {
let res = drop_tys_helper(
tcx,
query.value,
query.param_env,
adt_consider_insignificant_dtor(tcx),
true,
)
.filter(filter_array_elements(tcx, query.param_env))
.next()
.is_some();
debug!("has_significant_drop_raw({:?}) = {:?}", query, res);
res
}
struct NeedsDropTypes<'tcx, F> {
tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
query_ty: Ty<'tcx>,
seen_tys: FxHashSet<Ty<'tcx>>,
/// A stack of types left to process, and the recursion depth when we
/// pushed that type. Each round, we pop something from the stack and check
/// if it needs drop. If the result depends on whether some other types
/// need drop we push them onto the stack.
unchecked_tys: Vec<(Ty<'tcx>, usize)>,
recursion_limit: Limit,
adt_components: F,
}
impl<'tcx, F> NeedsDropTypes<'tcx, F> {
fn new(
tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
adt_components: F,
) -> Self {
let mut seen_tys = FxHashSet::default();
seen_tys.insert(ty);
Self {
tcx,
param_env,
seen_tys,
query_ty: ty,
unchecked_tys: vec![(ty, 0)],
recursion_limit: tcx.recursion_limit(),
adt_components,
}
}
}
impl<'tcx, F, I> Iterator for NeedsDropTypes<'tcx, F>
where
F: Fn(ty::AdtDef<'tcx>, GenericArgsRef<'tcx>) -> NeedsDropResult<I>,
I: Iterator<Item = Ty<'tcx>>,
{
type Item = NeedsDropResult<Ty<'tcx>>;
fn next(&mut self) -> Option<NeedsDropResult<Ty<'tcx>>> {
let tcx = self.tcx;
while let Some((ty, level)) = self.unchecked_tys.pop() {
if !self.recursion_limit.value_within_limit(level) {
// Not having a `Span` isn't great. But there's hopefully some other
// recursion limit error as well.
tcx.sess.emit_err(NeedsDropOverflow { query_ty: self.query_ty });
return Some(Err(AlwaysRequiresDrop));
}
let components = match needs_drop_components(tcx, ty) {
Err(e) => return Some(Err(e)),
Ok(components) => components,
};
debug!("needs_drop_components({:?}) = {:?}", ty, components);
let queue_type = move |this: &mut Self, component: Ty<'tcx>| {
if this.seen_tys.insert(component) {
this.unchecked_tys.push((component, level + 1));
}
};
for component in components {
2020-08-02 17:49:11 -05:00
match *component.kind() {
2022-09-11 10:22:38 -05:00
// The information required to determine whether a generator has drop is
2023-01-21 04:12:11 -06:00
// computed on MIR, while this very method is used to build MIR.
// To avoid cycles, we consider that generators always require drop.
2022-09-11 10:22:38 -05:00
ty::Generator(..) if tcx.sess.opts.unstable_opts.drop_tracking_mir => {
return Some(Err(AlwaysRequiresDrop));
}
_ if component.is_copy_modulo_regions(tcx, self.param_env) => (),
ty::Closure(_, args) => {
for upvar in args.as_closure().upvar_tys() {
queue_type(self, upvar);
}
}
ty::Generator(def_id, args, _) => {
let args = args.as_generator();
for upvar in args.upvar_tys() {
queue_type(self, upvar);
}
let witness = args.witness();
2020-08-02 17:49:11 -05:00
let interior_tys = match witness.kind() {
2020-10-23 19:21:18 -05:00
&ty::GeneratorWitness(tys) => tcx.erase_late_bound_regions(tys),
_ => {
tcx.sess.delay_span_bug(
tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP),
format!("unexpected generator witness type {witness:?}"),
);
return Some(Err(AlwaysRequiresDrop));
}
};
for interior_ty in interior_tys {
queue_type(self, interior_ty);
}
}
// Check for a `Drop` impl and whether this is a union or
// `ManuallyDrop`. If it's a struct or enum without a `Drop`
// impl then check whether the field types need `Drop`.
ty::Adt(adt_def, args) => {
let tys = match (self.adt_components)(adt_def, args) {
Err(e) => return Some(Err(e)),
Ok(tys) => tys,
};
for required_ty in tys {
let required = tcx
.try_normalize_erasing_regions(self.param_env, required_ty)
.unwrap_or(required_ty);
queue_type(self, required);
}
}
ty::Alias(..) | ty::Array(..) | ty::Placeholder(_) | ty::Param(_) => {
if ty == component {
// Return the type to the caller: they may be able
// to normalize further than we can.
return Some(Ok(component));
} else {
// Store the type for later. We can't return here
// because we would then lose any other components
// of the type.
queue_type(self, component);
}
}
2023-07-17 08:11:07 -05:00
ty::Foreign(_) | ty::Dynamic(..) => {
2023-07-17 08:11:07 -05:00
return Some(Err(AlwaysRequiresDrop));
}
ty::Bool
| ty::Char
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Str
| ty::Slice(_)
| ty::Ref(..)
| ty::RawPtr(..)
| ty::FnDef(..)
| ty::FnPtr(..)
| ty::Tuple(_)
| ty::Bound(..)
| ty::GeneratorWitness(..)
| ty::GeneratorWitnessMIR(..)
| ty::Never
| ty::Infer(_)
| ty::Error(_) => {
bug!("unexpected type returned by `needs_drop_components`: {component}")
}
}
}
}
None
}
}
enum DtorType {
/// Type has a `Drop` but it is considered insignificant.
/// Check the query `adt_significant_drop_tys` for understanding
/// "significant" / "insignificant".
Insignificant,
/// Type has a `Drop` implantation.
Significant,
}
// This is a helper function for `adt_drop_tys` and `adt_significant_drop_tys`.
// Depending on the implantation of `adt_has_dtor`, it is used to check if the
// ADT has a destructor or if the ADT only has a significant destructor. For
// understanding significant destructor look at `adt_significant_drop_tys`.
fn drop_tys_helper<'tcx>(
2021-09-21 04:06:19 -05:00
tcx: TyCtxt<'tcx>,
ty: Ty<'tcx>,
param_env: rustc_middle::ty::ParamEnv<'tcx>,
adt_has_dtor: impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType>,
only_significant: bool,
) -> impl Iterator<Item = NeedsDropResult<Ty<'tcx>>> {
fn with_query_cache<'tcx>(
tcx: TyCtxt<'tcx>,
iter: impl IntoIterator<Item = Ty<'tcx>>,
) -> NeedsDropResult<Vec<Ty<'tcx>>> {
iter.into_iter().try_fold(Vec::new(), |mut vec, subty| {
match subty.kind() {
ty::Adt(adt_id, subst) => {
for subty in tcx.adt_drop_tys(adt_id.did())? {
vec.push(EarlyBinder::bind(subty).instantiate(tcx, subst));
}
}
_ => vec.push(subty),
};
Ok(vec)
})
}
let adt_components = move |adt_def: ty::AdtDef<'tcx>, args: GenericArgsRef<'tcx>| {
if adt_def.is_manually_drop() {
debug!("drop_tys_helper: `{:?}` is manually drop", adt_def);
Ok(Vec::new())
} else if let Some(dtor_info) = adt_has_dtor(adt_def) {
match dtor_info {
DtorType::Significant => {
debug!("drop_tys_helper: `{:?}` implements `Drop`", adt_def);
Err(AlwaysRequiresDrop)
}
DtorType::Insignificant => {
debug!("drop_tys_helper: `{:?}` drop is insignificant", adt_def);
2021-09-21 04:06:19 -05:00
// Since the destructor is insignificant, we just want to make sure all of
// the passed in type parameters are also insignificant.
// Eg: Vec<T> dtor is insignificant when T=i32 but significant when T=Mutex.
Ok(args.types().collect())
}
}
} else if adt_def.is_union() {
debug!("drop_tys_helper: `{:?}` is a union", adt_def);
Ok(Vec::new())
} else {
let field_tys = adt_def.all_fields().map(|field| {
let r = tcx.type_of(field.did).instantiate(tcx, args);
debug!("drop_tys_helper: Subst into {:?} with {:?} getting {:?}", field, args, r);
r
});
if only_significant {
// We can't recurse through the query system here because we might induce a cycle
Ok(field_tys.collect())
} else {
// We can use the query system if we consider all drops significant. In that case,
// ADTs are `needs_drop` exactly if they `impl Drop` or if any of their "transitive"
// fields do. There can be no cycles here, because ADTs cannot contain themselves as
// fields.
with_query_cache(tcx, field_tys)
}
}
.map(|v| v.into_iter())
};
NeedsDropTypes::new(tcx, param_env, ty, adt_components)
}
fn adt_consider_insignificant_dtor<'tcx>(
tcx: TyCtxt<'tcx>,
) -> impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType> + 'tcx {
move |adt_def: ty::AdtDef<'tcx>| {
let is_marked_insig = tcx.has_attr(adt_def.did(), sym::rustc_insignificant_dtor);
2021-09-22 04:17:30 -05:00
if is_marked_insig {
// In some cases like `std::collections::HashMap` where the struct is a wrapper around
// a type that is a Drop type, and the wrapped type (eg: `hashbrown::HashMap`) lies
2022-10-13 11:25:34 -05:00
// outside stdlib, we might choose to still annotate the wrapper (std HashMap) with
2021-09-22 04:17:30 -05:00
// `rustc_insignificant_dtor`, even if the type itself doesn't have a `Drop` impl.
Some(DtorType::Insignificant)
} else if adt_def.destructor(tcx).is_some() {
// There is a Drop impl and the type isn't marked insignificant, therefore Drop must be
// significant.
Some(DtorType::Significant)
} else {
// No destructor found nor the type is annotated with `rustc_insignificant_dtor`, we
// treat this as the simple case of Drop impl for type.
None
}
}
}
fn adt_drop_tys<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
) -> Result<&ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
// This is for the "adt_drop_tys" query, that considers all `Drop` impls, therefore all dtors are
// significant.
let adt_has_dtor =
|adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
// `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_args)`
drop_tys_helper(
tcx,
tcx.type_of(def_id).instantiate_identity(),
tcx.param_env(def_id),
adt_has_dtor,
false,
)
.collect::<Result<Vec<_>, _>>()
Rename many interner functions. (This is a large commit. The changes to `compiler/rustc_middle/src/ty/context.rs` are the most important ones.) The current naming scheme is a mess, with a mix of `_intern_`, `intern_` and `mk_` prefixes, with little consistency. In particular, in many cases it's easy to use an iterator interner when a (preferable) slice interner is available. The guiding principles of the new naming system: - No `_intern_` prefixes. - The `intern_` prefix is for internal operations. - The `mk_` prefix is for external operations. - For cases where there is a slice interner and an iterator interner, the former is `mk_foo` and the latter is `mk_foo_from_iter`. Also, `slice_interners!` and `direct_interners!` can now be `pub` or non-`pub`, which helps enforce the internal/external operations division. It's not perfect, but I think it's a clear improvement. The following lists show everything that was renamed. slice_interners - const_list - mk_const_list -> mk_const_list_from_iter - intern_const_list -> mk_const_list - substs - mk_substs -> mk_substs_from_iter - intern_substs -> mk_substs - check_substs -> check_and_mk_substs (this is a weird one) - canonical_var_infos - intern_canonical_var_infos -> mk_canonical_var_infos - poly_existential_predicates - mk_poly_existential_predicates -> mk_poly_existential_predicates_from_iter - intern_poly_existential_predicates -> mk_poly_existential_predicates - _intern_poly_existential_predicates -> intern_poly_existential_predicates - predicates - mk_predicates -> mk_predicates_from_iter - intern_predicates -> mk_predicates - _intern_predicates -> intern_predicates - projs - intern_projs -> mk_projs - place_elems - mk_place_elems -> mk_place_elems_from_iter - intern_place_elems -> mk_place_elems - bound_variable_kinds - mk_bound_variable_kinds -> mk_bound_variable_kinds_from_iter - intern_bound_variable_kinds -> mk_bound_variable_kinds direct_interners - region - intern_region (unchanged) - const - mk_const_internal -> intern_const - const_allocation - intern_const_alloc -> mk_const_alloc - layout - intern_layout -> mk_layout - adt_def - intern_adt_def -> mk_adt_def_from_data (unusual case, hard to avoid) - alloc_adt_def(!) -> mk_adt_def - external_constraints - intern_external_constraints -> mk_external_constraints Other - type_list - mk_type_list -> mk_type_list_from_iter - intern_type_list -> mk_type_list - tup - mk_tup -> mk_tup_from_iter - intern_tup -> mk_tup
2023-02-16 21:33:08 -06:00
.map(|components| tcx.mk_type_list(&components))
}
// If `def_id` refers to a generic ADT, the queries above and below act as if they had been handed
// a `tcx.make_ty(def, identity_args)` and as such it is legal to substitute the generic parameters
// of the ADT into the outputted `ty`s.
fn adt_significant_drop_tys(
tcx: TyCtxt<'_>,
def_id: DefId,
) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
drop_tys_helper(
tcx,
tcx.type_of(def_id).instantiate_identity(), // identical to `tcx.make_adt(def, identity_args)`
tcx.param_env(def_id),
adt_consider_insignificant_dtor(tcx),
true,
)
.collect::<Result<Vec<_>, _>>()
Rename many interner functions. (This is a large commit. The changes to `compiler/rustc_middle/src/ty/context.rs` are the most important ones.) The current naming scheme is a mess, with a mix of `_intern_`, `intern_` and `mk_` prefixes, with little consistency. In particular, in many cases it's easy to use an iterator interner when a (preferable) slice interner is available. The guiding principles of the new naming system: - No `_intern_` prefixes. - The `intern_` prefix is for internal operations. - The `mk_` prefix is for external operations. - For cases where there is a slice interner and an iterator interner, the former is `mk_foo` and the latter is `mk_foo_from_iter`. Also, `slice_interners!` and `direct_interners!` can now be `pub` or non-`pub`, which helps enforce the internal/external operations division. It's not perfect, but I think it's a clear improvement. The following lists show everything that was renamed. slice_interners - const_list - mk_const_list -> mk_const_list_from_iter - intern_const_list -> mk_const_list - substs - mk_substs -> mk_substs_from_iter - intern_substs -> mk_substs - check_substs -> check_and_mk_substs (this is a weird one) - canonical_var_infos - intern_canonical_var_infos -> mk_canonical_var_infos - poly_existential_predicates - mk_poly_existential_predicates -> mk_poly_existential_predicates_from_iter - intern_poly_existential_predicates -> mk_poly_existential_predicates - _intern_poly_existential_predicates -> intern_poly_existential_predicates - predicates - mk_predicates -> mk_predicates_from_iter - intern_predicates -> mk_predicates - _intern_predicates -> intern_predicates - projs - intern_projs -> mk_projs - place_elems - mk_place_elems -> mk_place_elems_from_iter - intern_place_elems -> mk_place_elems - bound_variable_kinds - mk_bound_variable_kinds -> mk_bound_variable_kinds_from_iter - intern_bound_variable_kinds -> mk_bound_variable_kinds direct_interners - region - intern_region (unchanged) - const - mk_const_internal -> intern_const - const_allocation - intern_const_alloc -> mk_const_alloc - layout - intern_layout -> mk_layout - adt_def - intern_adt_def -> mk_adt_def_from_data (unusual case, hard to avoid) - alloc_adt_def(!) -> mk_adt_def - external_constraints - intern_external_constraints -> mk_external_constraints Other - type_list - mk_type_list -> mk_type_list_from_iter - intern_type_list -> mk_type_list - tup - mk_tup -> mk_tup_from_iter - intern_tup -> mk_tup
2023-02-16 21:33:08 -06:00
.map(|components| tcx.mk_type_list(&components))
}
pub(crate) fn provide(providers: &mut Providers) {
*providers = Providers {
2021-09-02 06:04:29 -05:00
needs_drop_raw,
has_significant_drop_raw,
adt_drop_tys,
adt_significant_drop_tys,
..*providers
};
}