rust/compiler/rustc_const_eval/src/interpret/util.rs

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

72 lines
2.8 KiB
Rust
Raw Normal View History

use rustc_middle::mir::interpret::InterpResult;
2022-06-17 12:15:00 +00:00
use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor};
use std::ops::ControlFlow;
2022-01-20 13:47:31 +00:00
/// Checks whether a type contains generic parameters which require substitution.
///
/// In case it does, returns a `TooGeneric` const eval error. Note that due to polymorphization
/// types may be "concrete enough" even though they still contain generic parameters in
/// case these parameters are unused.
pub(crate) fn ensure_monomorphic_enough<'tcx, T>(tcx: TyCtxt<'tcx>, ty: T) -> InterpResult<'tcx>
where
T: TypeVisitable<'tcx>,
{
debug!("ensure_monomorphic_enough: ty={:?}", ty);
2022-01-12 03:19:52 +00:00
if !ty.needs_subst() {
return Ok(());
}
2020-12-06 20:31:42 +00:00
struct FoundParam;
struct UsedParamsNeedSubstVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
impl<'tcx> TypeVisitor<'tcx> for UsedParamsNeedSubstVisitor<'tcx> {
2020-12-06 20:31:42 +00:00
type BreakTy = FoundParam;
2020-11-14 20:46:39 +00:00
2020-11-05 16:30:39 +00:00
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2022-01-12 03:19:52 +00:00
if !ty.needs_subst() {
return ControlFlow::CONTINUE;
}
2020-08-02 22:49:11 +00:00
match *ty.kind() {
2020-12-06 20:31:42 +00:00
ty::Param(_) => ControlFlow::Break(FoundParam),
ty::Closure(def_id, substs)
| ty::Generator(def_id, substs, ..)
| ty::FnDef(def_id, substs) => {
let instance = ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id));
let unused_params = self.tcx.unused_generic_params(instance);
for (index, subst) in substs.into_iter().enumerate() {
let index = index
.try_into()
.expect("more generic parameters than can fit into a `u32`");
// Only recurse when generic parameters in fns, closures and generators
// are used and require substitution.
// Just in case there are closures or generators within this subst,
// recurse.
if unused_params.is_used(index) && subst.needs_subst() {
return subst.visit_with(self);
}
}
ControlFlow::CONTINUE
}
_ => ty.super_visit_with(self),
}
}
fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
match c.kind() {
ty::ConstKind::Param(..) => ControlFlow::Break(FoundParam),
_ => c.super_visit_with(self),
}
}
}
let mut vis = UsedParamsNeedSubstVisitor { tcx };
2020-12-06 20:31:42 +00:00
if matches!(ty.visit_with(&mut vis), ControlFlow::Break(FoundParam)) {
throw_inval!(TooGeneric);
} else {
Ok(())
}
}