use rustc_hir::def_id::DefId;
use rustc_middle::ty::{self, Ty, TyVid};
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use crate::infer::InferCtxtUndoLogs;
use rustc_data_structures::snapshot_vec as sv;
use rustc_data_structures::unify as ut;
use std::cmp;
use std::marker::PhantomData;
use std::ops::Range;
use rustc_data_structures::undo_log::{Rollback, UndoLogs};
pub(crate) enum UndoLog<'tcx> {
EqRelation(sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>),
SubRelation(sv::UndoLog<ut::Delegate<ty::TyVid>>),
Values(sv::UndoLog<Delegate>),
}
impl<'tcx> From<sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>> for UndoLog<'tcx> {
fn from(l: sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>) -> Self {
UndoLog::EqRelation(l)
}
}
impl<'tcx> From<sv::UndoLog<ut::Delegate<ty::TyVid>>> for UndoLog<'tcx> {
fn from(l: sv::UndoLog<ut::Delegate<ty::TyVid>>) -> Self {
UndoLog::SubRelation(l)
}
}
impl<'tcx> From<sv::UndoLog<Delegate>> for UndoLog<'tcx> {
fn from(l: sv::UndoLog<Delegate>) -> Self {
UndoLog::Values(l)
}
}
impl<'tcx> From<Instantiate> for UndoLog<'tcx> {
fn from(l: Instantiate) -> Self {
UndoLog::Values(sv::UndoLog::Other(l))
}
}
impl<'tcx> Rollback<UndoLog<'tcx>> for TypeVariableStorage<'tcx> {
fn reverse(&mut self, undo: UndoLog<'tcx>) {
match undo {
UndoLog::EqRelation(undo) => self.eq_relations.reverse(undo),
UndoLog::SubRelation(undo) => self.sub_relations.reverse(undo),
UndoLog::Values(undo) => self.values.reverse(undo),
}
}
}
pub struct TypeVariableStorage<'tcx> {
values: sv::SnapshotVecStorage<Delegate>,
eq_relations: ut::UnificationTableStorage<TyVidEqKey<'tcx>>,
sub_relations: ut::UnificationTableStorage<ty::TyVid>,
}
pub struct TypeVariableTable<'a, 'tcx> {
storage: &'a mut TypeVariableStorage<'tcx>,
undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
}
#[derive(Copy, Clone, Debug)]
pub struct TypeVariableOrigin {
pub kind: TypeVariableOriginKind,
pub span: Span,
}
#[derive(Copy, Clone, Debug)]
pub enum TypeVariableOriginKind {
MiscVariable,
NormalizeProjectionType,
TypeInference,
TypeParameterDefinition(Symbol, Option<DefId>),
ClosureSynthetic,
SubstitutionPlaceholder,
AutoDeref,
AdjustmentType,
DivergingFn,
LatticeVariable,
}
pub(crate) struct TypeVariableData {
origin: TypeVariableOrigin,
diverging: bool,
}
#[derive(Copy, Clone, Debug)]
pub enum TypeVariableValue<'tcx> {
Known { value: Ty<'tcx> },
Unknown { universe: ty::UniverseIndex },
}
impl<'tcx> TypeVariableValue<'tcx> {
pub fn known(&self) -> Option<Ty<'tcx>> {
match *self {
TypeVariableValue::Unknown { .. } => None,
TypeVariableValue::Known { value } => Some(value),
}
}
pub fn is_unknown(&self) -> bool {
match *self {
TypeVariableValue::Unknown { .. } => true,
TypeVariableValue::Known { .. } => false,
}
}
}
pub(crate) struct Instantiate {
vid: ty::TyVid,
}
pub(crate) struct Delegate;
impl<'tcx> TypeVariableStorage<'tcx> {
pub fn new() -> TypeVariableStorage<'tcx> {
TypeVariableStorage {
values: sv::SnapshotVecStorage::new(),
eq_relations: ut::UnificationTableStorage::new(),
sub_relations: ut::UnificationTableStorage::new(),
}
}
#[inline]
pub(crate) fn with_log<'a>(
&'a mut self,
undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
) -> TypeVariableTable<'a, 'tcx> {
TypeVariableTable { storage: self, undo_log }
}
}
impl<'tcx> TypeVariableTable<'_, 'tcx> {
pub fn var_diverges(&self, vid: ty::TyVid) -> bool {
self.storage.values.get(vid.index as usize).diverging
}
pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin {
&self.storage.values.get(vid.index as usize).origin
}
pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
debug_assert!(self.probe(a).is_unknown());
debug_assert!(self.probe(b).is_unknown());
self.eq_relations().union(a, b);
self.sub_relations().union(a, b);
}
pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) {
debug_assert!(self.probe(a).is_unknown());
debug_assert!(self.probe(b).is_unknown());
self.sub_relations().union(a, b);
}
pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
let vid = self.root_var(vid);
debug_assert!(self.probe(vid).is_unknown());
debug_assert!(
self.eq_relations().probe_value(vid).is_unknown(),
"instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}",
vid,
ty,
self.eq_relations().probe_value(vid)
);
self.eq_relations().union_value(vid, TypeVariableValue::Known { value: ty });
self.undo_log.push(Instantiate { vid });
}
pub fn new_var(
&mut self,
universe: ty::UniverseIndex,
diverging: bool,
origin: TypeVariableOrigin,
) -> ty::TyVid {
let eq_key = self.eq_relations().new_key(TypeVariableValue::Unknown { universe });
let sub_key = self.sub_relations().new_key(());
assert_eq!(eq_key.vid, sub_key);
let index = self.values().push(TypeVariableData { origin, diverging });
assert_eq!(eq_key.vid.index, index as u32);
debug!(
"new_var(index={:?}, universe={:?}, diverging={:?}, origin={:?}",
eq_key.vid, universe, diverging, origin,
);
eq_key.vid
}
pub fn num_vars(&self) -> usize {
self.storage.values.len()
}
pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
self.eq_relations().find(vid).vid
}
pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
self.sub_relations().find(vid)
}
pub fn sub_unified(&mut self, a: ty::TyVid, b: ty::TyVid) -> bool {
self.sub_root_var(a) == self.sub_root_var(b)
}
pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
self.inlined_probe(vid)
}
#[inline(always)]
pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
self.eq_relations().inlined_probe_value(vid)
}
pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
match *t.kind() {
ty::Infer(ty::TyVar(v)) => match self.probe(v) {
TypeVariableValue::Unknown { .. } => t,
TypeVariableValue::Known { value } => value,
},
_ => t,
}
}
#[inline]
fn values(
&mut self,
) -> sv::SnapshotVec<Delegate, &mut Vec<TypeVariableData>, &mut InferCtxtUndoLogs<'tcx>> {
self.storage.values.with_log(self.undo_log)
}
#[inline]
fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> {
self.storage.eq_relations.with_log(self.undo_log)
}
#[inline]
fn sub_relations(&mut self) -> super::UnificationTable<'_, 'tcx, ty::TyVid> {
self.storage.sub_relations.with_log(self.undo_log)
}
pub fn vars_since_snapshot(
&mut self,
value_count: usize,
) -> (Range<TyVid>, Vec<TypeVariableOrigin>) {
let range = TyVid { index: value_count as u32 }..TyVid { index: self.num_vars() as u32 };
(
range.start..range.end,
(range.start.index..range.end.index)
.map(|index| self.storage.values.get(index as usize).origin)
.collect(),
)
}
pub fn types_escaping_snapshot(&mut self, s: &super::Snapshot<'tcx>) -> Vec<Ty<'tcx>> {
let mut new_elem_threshold = u32::MAX;
let mut escaping_types = Vec::new();
let actions_since_snapshot = self.undo_log.actions_since_snapshot(s);
debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len());
for i in 0..actions_since_snapshot.len() {
let actions_since_snapshot = self.undo_log.actions_since_snapshot(s);
match actions_since_snapshot[i] {
super::UndoLog::TypeVariables(UndoLog::Values(sv::UndoLog::NewElem(index))) => {
new_elem_threshold = cmp::min(new_elem_threshold, index as u32);
debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
}
super::UndoLog::TypeVariables(UndoLog::Values(sv::UndoLog::Other(
Instantiate { vid, .. },
))) => {
if vid.index < new_elem_threshold {
let mut eq_relations = ut::UnificationTable::with_log(
&mut self.storage.eq_relations,
&mut *self.undo_log,
);
let escaping_type = match eq_relations.probe_value(vid) {
TypeVariableValue::Unknown { .. } => bug!(),
TypeVariableValue::Known { value } => value,
};
escaping_types.push(escaping_type);
}
debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold);
}
_ => {}
}
}
escaping_types
}
pub fn unsolved_variables(&mut self) -> Vec<ty::TyVid> {
(0..self.storage.values.len())
.filter_map(|i| {
let vid = ty::TyVid { index: i as u32 };
match self.probe(vid) {
TypeVariableValue::Unknown { .. } => Some(vid),
TypeVariableValue::Known { .. } => None,
}
})
.collect()
}
}
impl sv::SnapshotVecDelegate for Delegate {
type Value = TypeVariableData;
type Undo = Instantiate;
fn reverse(_values: &mut Vec<TypeVariableData>, _action: Instantiate) {
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) struct TyVidEqKey<'tcx> {
vid: ty::TyVid,
phantom: PhantomData<TypeVariableValue<'tcx>>,
}
impl<'tcx> From<ty::TyVid> for TyVidEqKey<'tcx> {
fn from(vid: ty::TyVid) -> Self {
TyVidEqKey { vid, phantom: PhantomData }
}
}
impl<'tcx> ut::UnifyKey for TyVidEqKey<'tcx> {
type Value = TypeVariableValue<'tcx>;
fn index(&self) -> u32 {
self.vid.index
}
fn from_index(i: u32) -> Self {
TyVidEqKey::from(ty::TyVid { index: i })
}
fn tag() -> &'static str {
"TyVidEqKey"
}
}
impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> {
type Error = ut::NoError;
fn unify_values(value1: &Self, value2: &Self) -> Result<Self, ut::NoError> {
match (value1, value2) {
(&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => {
bug!("equating two type variables, both of which have known types")
}
(&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1),
(&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2),
(
&TypeVariableValue::Unknown { universe: universe1 },
&TypeVariableValue::Unknown { universe: universe2 },
) => {
let universe = cmp::min(universe1, universe2);
Ok(TypeVariableValue::Unknown { universe })
}
}
}
}