remove the subtyping relations from TypeVariable

This commit is contained in:
Niko Matsakis 2017-03-16 09:05:39 -04:00
parent 105ec7e3bb
commit e58e2b423d
6 changed files with 51 additions and 130 deletions

View File

@ -38,7 +38,6 @@ use super::lub::Lub;
use super::sub::Sub; use super::sub::Sub;
use super::InferCtxt; use super::InferCtxt;
use super::{MiscVariable, TypeTrace}; use super::{MiscVariable, TypeTrace};
use super::type_variable::{RelationDir, BiTo, EqTo, SubtypeOf, SupertypeOf};
use ty::{IntType, UintType}; use ty::{IntType, UintType};
use ty::{self, Ty, TyCtxt}; use ty::{self, Ty, TyCtxt};
@ -59,6 +58,11 @@ pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
pub obligations: PredicateObligations<'tcx>, pub obligations: PredicateObligations<'tcx>,
} }
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum RelationDir {
SubtypeOf, SupertypeOf, EqTo
}
impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> { impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
pub fn super_combine_tys<R>(&self, pub fn super_combine_tys<R>(&self,
relation: &mut R, relation: &mut R,
@ -177,6 +181,8 @@ impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
a_is_expected: bool) a_is_expected: bool)
-> RelateResult<'tcx, ()> -> RelateResult<'tcx, ()>
{ {
use self::RelationDir::*;
// We use SmallVector here instead of Vec because this code is hot and // We use SmallVector here instead of Vec because this code is hot and
// it's rare that the stack length exceeds 1. // it's rare that the stack length exceeds 1.
let mut stack = SmallVector::new(); let mut stack = SmallVector::new();
@ -224,7 +230,7 @@ impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
// Generalize type if necessary. // Generalize type if necessary.
let generalized_ty = match dir { let generalized_ty = match dir {
EqTo => self.generalize(a_ty, b_vid, false), EqTo => self.generalize(a_ty, b_vid, false),
BiTo | SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true), SupertypeOf | SubtypeOf => self.generalize(a_ty, b_vid, true),
}?; }?;
debug!("instantiate(a_ty={:?}, dir={:?}, \ debug!("instantiate(a_ty={:?}, dir={:?}, \
b_vid={:?}, generalized_ty={:?})", b_vid={:?}, generalized_ty={:?})",
@ -232,8 +238,7 @@ impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
generalized_ty); generalized_ty);
self.infcx.type_variables self.infcx.type_variables
.borrow_mut() .borrow_mut()
.instantiate_and_push( .instantiate(b_vid, generalized_ty);
b_vid, generalized_ty, &mut stack);
generalized_ty generalized_ty
} }
}; };
@ -246,7 +251,6 @@ impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
// to associate causes/spans with each of the relations in // to associate causes/spans with each of the relations in
// the stack to get this right. // the stack to get this right.
match dir { match dir {
BiTo => Ok(a_ty),
EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty), EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty), SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
SupertypeOf => self.sub(a_is_expected).relate_with_variance( SupertypeOf => self.sub(a_is_expected).relate_with_variance(

View File

@ -8,9 +8,8 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
use super::combine::CombineFields; use super::combine::{CombineFields, RelationDir};
use super::{Subtype}; use super::{Subtype};
use super::type_variable::{EqTo};
use ty::{self, Ty, TyCtxt}; use ty::{self, Ty, TyCtxt};
use ty::TyVar; use ty::TyVar;
@ -58,17 +57,17 @@ impl<'combine, 'infcx, 'gcx, 'tcx> TypeRelation<'infcx, 'gcx, 'tcx>
let b = infcx.type_variables.borrow_mut().replace_if_possible(b); let b = infcx.type_variables.borrow_mut().replace_if_possible(b);
match (&a.sty, &b.sty) { match (&a.sty, &b.sty) {
(&ty::TyInfer(TyVar(a_id)), &ty::TyInfer(TyVar(b_id))) => { (&ty::TyInfer(TyVar(a_id)), &ty::TyInfer(TyVar(b_id))) => {
infcx.type_variables.borrow_mut().relate_vars(a_id, EqTo, b_id); infcx.type_variables.borrow_mut().equate(a_id, b_id);
Ok(a) Ok(a)
} }
(&ty::TyInfer(TyVar(a_id)), _) => { (&ty::TyInfer(TyVar(a_id)), _) => {
self.fields.instantiate(b, EqTo, a_id, self.a_is_expected)?; self.fields.instantiate(b, RelationDir::EqTo, a_id, self.a_is_expected)?;
Ok(a) Ok(a)
} }
(_, &ty::TyInfer(TyVar(b_id))) => { (_, &ty::TyInfer(TyVar(b_id))) => {
self.fields.instantiate(a, EqTo, b_id, self.a_is_expected)?; self.fields.instantiate(a, RelationDir::EqTo, b_id, self.a_is_expected)?;
Ok(a) Ok(a)
} }

View File

@ -9,8 +9,7 @@
// except according to those terms. // except according to those terms.
use super::SubregionOrigin; use super::SubregionOrigin;
use super::combine::CombineFields; use super::combine::{CombineFields, RelationDir};
use super::type_variable::{SubtypeOf, SupertypeOf};
use traits::Obligation; use traits::Obligation;
use ty::{self, Ty, TyCtxt}; use ty::{self, Ty, TyCtxt};
@ -104,11 +103,11 @@ impl<'combine, 'infcx, 'gcx, 'tcx> TypeRelation<'infcx, 'gcx, 'tcx>
} }
(&ty::TyInfer(TyVar(a_id)), _) => { (&ty::TyInfer(TyVar(a_id)), _) => {
self.fields self.fields
.instantiate(b, SupertypeOf, a_id, !self.a_is_expected)?; .instantiate(b, RelationDir::SupertypeOf, a_id, !self.a_is_expected)?;
Ok(a) Ok(a)
} }
(_, &ty::TyInfer(TyVar(b_id))) => { (_, &ty::TyInfer(TyVar(b_id))) => {
self.fields.instantiate(a, SubtypeOf, b_id, self.a_is_expected)?; self.fields.instantiate(a, RelationDir::SubtypeOf, b_id, self.a_is_expected)?;
Ok(a) Ok(a)
} }

View File

@ -8,11 +8,8 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
pub use self::RelationDir::*;
use self::TypeVariableValue::*; use self::TypeVariableValue::*;
use self::UndoEntry::*;
use hir::def_id::{DefId}; use hir::def_id::{DefId};
use syntax::util::small_vector::SmallVector;
use syntax::ast; use syntax::ast;
use syntax_pos::Span; use syntax_pos::Span;
use ty::{self, Ty}; use ty::{self, Ty};
@ -55,7 +52,6 @@ struct TypeVariableData<'tcx> {
enum TypeVariableValue<'tcx> { enum TypeVariableValue<'tcx> {
Known(Ty<'tcx>), Known(Ty<'tcx>),
Bounded { Bounded {
relations: Vec<Relation>,
default: Option<Default<'tcx>> default: Option<Default<'tcx>>
} }
} }
@ -76,33 +72,13 @@ pub struct Snapshot {
eq_snapshot: ut::Snapshot<ty::TyVid>, eq_snapshot: ut::Snapshot<ty::TyVid>,
} }
enum UndoEntry<'tcx> { struct Instantiate<'tcx> {
// The type of the var was specified. vid: ty::TyVid,
SpecifyVar(ty::TyVid, Vec<Relation>, Option<Default<'tcx>>), default: Option<Default<'tcx>>,
Relate(ty::TyVid, ty::TyVid),
RelateRange(ty::TyVid, usize),
} }
struct Delegate<'tcx>(PhantomData<&'tcx ()>); struct Delegate<'tcx>(PhantomData<&'tcx ()>);
type Relation = (RelationDir, ty::TyVid);
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum RelationDir {
SubtypeOf, SupertypeOf, EqTo, BiTo
}
impl RelationDir {
fn opposite(self) -> RelationDir {
match self {
SubtypeOf => SupertypeOf,
SupertypeOf => SubtypeOf,
EqTo => EqTo,
BiTo => BiTo,
}
}
}
impl<'tcx> TypeVariableTable<'tcx> { impl<'tcx> TypeVariableTable<'tcx> {
pub fn new() -> TypeVariableTable<'tcx> { pub fn new() -> TypeVariableTable<'tcx> {
TypeVariableTable { TypeVariableTable {
@ -111,10 +87,6 @@ impl<'tcx> TypeVariableTable<'tcx> {
} }
} }
fn relations<'a>(&'a mut self, a: ty::TyVid) -> &'a mut Vec<Relation> {
relations(self.values.get_mut(a.index as usize))
}
pub fn default(&self, vid: ty::TyVid) -> Option<Default<'tcx>> { pub fn default(&self, vid: ty::TyVid) -> Option<Default<'tcx>> {
match &self.values.get(vid.index as usize).value { match &self.values.get(vid.index as usize).value {
&Known(_) => None, &Known(_) => None,
@ -130,68 +102,37 @@ impl<'tcx> TypeVariableTable<'tcx> {
&self.values.get(vid.index as usize).origin &self.values.get(vid.index as usize).origin
} }
/// Records that `a <: b`, `a :> b`, or `a == b`, depending on `dir`. /// Records that `a == b`, depending on `dir`.
/// ///
/// Precondition: neither `a` nor `b` are known. /// Precondition: neither `a` nor `b` are known.
pub fn relate_vars(&mut self, a: ty::TyVid, dir: RelationDir, b: ty::TyVid) { pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
let a = self.root_var(a); debug_assert!(self.probe(a).is_none());
let b = self.root_var(b); debug_assert!(self.probe(b).is_none());
if a != b { self.eq_relations.union(a, b);
if dir == EqTo {
// a and b must be equal which we mark in the unification table
let root = self.eq_relations.union(a, b);
// In addition to being equal, all relations from the variable which is no longer
// the root must be added to the root so they are not forgotten as the other
// variable should no longer be referenced (other than to get the root)
let other = if a == root { b } else { a };
let count = {
let (relations, root_relations) = if other.index < root.index {
let (pre, post) = self.values.split_at_mut(root.index as usize);
(relations(&mut pre[other.index as usize]), relations(&mut post[0]))
} else {
let (pre, post) = self.values.split_at_mut(other.index as usize);
(relations(&mut post[0]), relations(&mut pre[root.index as usize]))
};
root_relations.extend_from_slice(relations);
relations.len()
};
self.values.record(RelateRange(root, count));
} else {
self.relations(a).push((dir, b));
self.relations(b).push((dir.opposite(), a));
self.values.record(Relate(a, b));
}
}
} }
/// Instantiates `vid` with the type `ty` and then pushes an entry onto `stack` for each of the /// Instantiates `vid` with the type `ty`.
/// relations of `vid` to other variables. The relations will have the form `(ty, dir, vid1)`
/// where `vid1` is some other variable id.
/// ///
/// Precondition: `vid` must be a root in the unification table /// Precondition: `vid` must be a root in the unification table
pub fn instantiate_and_push( /// and has not previously been instantiated.
&mut self, pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
vid: ty::TyVid,
ty: Ty<'tcx>,
stack: &mut SmallVector<(Ty<'tcx>, RelationDir, ty::TyVid)>)
{
debug_assert!(self.root_var(vid) == vid); debug_assert!(self.root_var(vid) == vid);
debug_assert!(self.probe(vid).is_none());
let old_value = { let old_value = {
let value_ptr = &mut self.values.get_mut(vid.index as usize).value; let vid_data = &mut self.values[vid.index as usize];
mem::replace(value_ptr, Known(ty)) mem::replace(&mut vid_data.value, TypeVariableValue::Known(ty))
}; };
let (relations, default) = match old_value { match old_value {
Bounded { relations, default } => (relations, default), TypeVariableValue::Bounded { default } => {
Known(_) => bug!("Asked to instantiate variable that is \ self.values.record(Instantiate { vid: vid, default: default });
already instantiated") }
}; TypeVariableValue::Known(old_ty) => {
bug!("instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}",
for &(dir, vid) in &relations { vid, ty, old_ty)
stack.push((ty, dir, vid)); }
} }
self.values.record(SpecifyVar(vid, relations, default));
} }
pub fn new_var(&mut self, pub fn new_var(&mut self,
@ -201,7 +142,7 @@ impl<'tcx> TypeVariableTable<'tcx> {
debug!("new_var(diverging={:?}, origin={:?})", diverging, origin); debug!("new_var(diverging={:?}, origin={:?})", diverging, origin);
self.eq_relations.new_key(()); self.eq_relations.new_key(());
let index = self.values.push(TypeVariableData { let index = self.values.push(TypeVariableData {
value: Bounded { relations: vec![], default: default }, value: Bounded { default: default },
origin: origin, origin: origin,
diverging: diverging diverging: diverging
}); });
@ -298,7 +239,7 @@ impl<'tcx> TypeVariableTable<'tcx> {
debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold); debug!("NewElem({}) new_elem_threshold={}", index, new_elem_threshold);
} }
sv::UndoLog::Other(SpecifyVar(vid, ..)) => { sv::UndoLog::Other(Instantiate { vid, .. }) => {
if vid.index < new_elem_threshold { if vid.index < new_elem_threshold {
// quick check to see if this variable was // quick check to see if this variable was
// created since the snapshot started or not. // created since the snapshot started or not.
@ -334,35 +275,12 @@ impl<'tcx> TypeVariableTable<'tcx> {
impl<'tcx> sv::SnapshotVecDelegate for Delegate<'tcx> { impl<'tcx> sv::SnapshotVecDelegate for Delegate<'tcx> {
type Value = TypeVariableData<'tcx>; type Value = TypeVariableData<'tcx>;
type Undo = UndoEntry<'tcx>; type Undo = Instantiate<'tcx>;
fn reverse(values: &mut Vec<TypeVariableData<'tcx>>, action: UndoEntry<'tcx>) { fn reverse(values: &mut Vec<TypeVariableData<'tcx>>, action: Instantiate<'tcx>) {
match action { let Instantiate { vid, default } = action;
SpecifyVar(vid, relations, default) => { values[vid.index as usize].value = Bounded {
values[vid.index as usize].value = Bounded { default: default
relations: relations, };
default: default
};
}
Relate(a, b) => {
relations(&mut (*values)[a.index as usize]).pop();
relations(&mut (*values)[b.index as usize]).pop();
}
RelateRange(i, n) => {
let relations = relations(&mut (*values)[i.index as usize]);
for _ in 0..n {
relations.pop();
}
}
}
}
}
fn relations<'a>(v: &'a mut TypeVariableData) -> &'a mut Vec<Relation> {
match v.value {
Known(_) => bug!("var_sub_var: variable is known"),
Bounded { ref mut relations, .. } => relations
} }
} }

View File

@ -32,6 +32,7 @@
#![feature(i128_type)] #![feature(i128_type)]
#![feature(libc)] #![feature(libc)]
#![feature(loop_break_value)] #![feature(loop_break_value)]
#![feature(never_type)]
#![feature(nonzero)] #![feature(nonzero)]
#![cfg_attr(stage0, feature(pub_restricted))] #![cfg_attr(stage0, feature(pub_restricted))]
#![feature(quote)] #![feature(quote)]

View File

@ -9,7 +9,7 @@
// except according to those terms. // except according to those terms.
fn main() { fn main() {
let v = &[]; let v = &[]; //~ NOTE consider giving `v` a type
//~^ NOTE consider giving `it` a type let it = v.iter(); //~ ERROR type annotations needed
let it = v.iter(); //~ ERROR cannot infer type for `_` //~^ NOTE cannot infer type for `_`
} }