Skip to content

Commit

Permalink
add support for principal-less trait object types
Browse files Browse the repository at this point in the history
should be a pure refactoring.
  • Loading branch information
arielb1 committed Jan 3, 2019
1 parent c0bbc39 commit 3aa1503
Show file tree
Hide file tree
Showing 26 changed files with 203 additions and 132 deletions.
8 changes: 7 additions & 1 deletion src/librustc/traits/coherence.rs
Expand Up @@ -485,7 +485,13 @@ fn ty_is_local_constructor(ty: Ty<'_>, in_crate: InCrate) -> bool {
ty::Adt(def, _) => def_id_is_local(def.did, in_crate),
ty::Foreign(did) => def_id_is_local(did, in_crate),

ty::Dynamic(ref tt, ..) => def_id_is_local(tt.principal().def_id(), in_crate),
ty::Dynamic(ref tt, ..) => {
if let Some(principal) = tt.principal() {
def_id_is_local(principal.def_id(), in_crate)
} else {
false
}
}

ty::Error => true,

Expand Down
21 changes: 15 additions & 6 deletions src/librustc/traits/select.rs
Expand Up @@ -2016,7 +2016,12 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
return;
}

data.principal().with_self_ty(self.tcx(), self_ty)
if let Some(principal) = data.principal() {
principal.with_self_ty(self.tcx(), self_ty)
} else {
// Only auto-trait bounds exist.
return;
}
}
ty::Infer(ty::TyVar(_)) => {
debug!("assemble_candidates_from_object_ty: ambiguous");
Expand Down Expand Up @@ -2108,7 +2113,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
//
// We always upcast when we can because of reason
// #2 (region bounds).
data_a.principal().def_id() == data_b.principal().def_id()
data_a.principal_def_id() == data_b.principal_def_id()
&& data_b.auto_traits()
// All of a's auto traits need to be in b's auto traits.
.all(|b| data_a.auto_traits().any(|a| a == b))
Expand Down Expand Up @@ -2919,7 +2924,10 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
let self_ty = self.infcx
.shallow_resolve(*obligation.self_ty().skip_binder());
let poly_trait_ref = match self_ty.sty {
ty::Dynamic(ref data, ..) => data.principal().with_self_ty(self.tcx(), self_ty),
ty::Dynamic(ref data, ..) =>
data.principal().unwrap_or_else(|| {
span_bug!(obligation.cause.span, "object candidate with no principal")
}).with_self_ty(self.tcx(), self_ty),
_ => span_bug!(obligation.cause.span, "object candidate with non-object"),
};

Expand Down Expand Up @@ -3222,8 +3230,9 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
(&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
// See assemble_candidates_for_unsizing for more info.
let existential_predicates = data_a.map_bound(|data_a| {
let iter = iter::once(ty::ExistentialPredicate::Trait(data_a.principal()))
.chain(
let iter =
data_a.principal().map(|x| ty::ExistentialPredicate::Trait(x))
.into_iter().chain(
data_a
.projection_bounds()
.map(|x| ty::ExistentialPredicate::Projection(x)),
Expand Down Expand Up @@ -3260,7 +3269,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
// T -> Trait.
(_, &ty::Dynamic(ref data, r)) => {
let mut object_dids = data.auto_traits()
.chain(iter::once(data.principal().def_id()));
.chain(data.principal_def_id());
if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
return Err(TraitNotObjectSafe(did));
}
Expand Down
6 changes: 5 additions & 1 deletion src/librustc/ty/error.rs
Expand Up @@ -183,7 +183,11 @@ impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
ty::FnDef(..) => "fn item".into(),
ty::FnPtr(_) => "fn pointer".into(),
ty::Dynamic(ref inner, ..) => {
format!("trait {}", tcx.item_path_str(inner.principal().def_id())).into()
if let Some(principal) = inner.principal() {
format!("trait {}", tcx.item_path_str(principal.def_id())).into()
} else {
"trait".into()
}
}
ty::Closure(..) => "closure".into(),
ty::Generator(..) => "generator".into(),
Expand Down
12 changes: 6 additions & 6 deletions src/librustc/ty/fast_reject.rs
Expand Up @@ -71,11 +71,11 @@ pub fn simplify_type<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
ty::Array(..) | ty::Slice(_) => Some(ArraySimplifiedType),
ty::RawPtr(_) => Some(PtrSimplifiedType),
ty::Dynamic(ref trait_info, ..) => {
let principal_def_id = trait_info.principal().def_id();
if tcx.trait_is_auto(principal_def_id) {
Some(MarkerTraitObjectSimplifiedType)
} else {
Some(TraitSimplifiedType(principal_def_id))
match trait_info.principal_def_id() {
Some(principal_def_id) if !tcx.trait_is_auto(principal_def_id) => {
Some(TraitSimplifiedType(principal_def_id))
}
_ => Some(MarkerTraitObjectSimplifiedType)
}
}
ty::Ref(_, ty, _) => {
Expand Down Expand Up @@ -140,9 +140,9 @@ impl<D: Copy + Debug + Ord + Eq + Hash> SimplifiedTypeGen<D> {
ArraySimplifiedType => ArraySimplifiedType,
PtrSimplifiedType => PtrSimplifiedType,
NeverSimplifiedType => NeverSimplifiedType,
MarkerTraitObjectSimplifiedType => MarkerTraitObjectSimplifiedType,
TupleSimplifiedType(n) => TupleSimplifiedType(n),
TraitSimplifiedType(d) => TraitSimplifiedType(map(d)),
MarkerTraitObjectSimplifiedType => MarkerTraitObjectSimplifiedType,
ClosureSimplifiedType(d) => ClosureSimplifiedType(map(d)),
GeneratorSimplifiedType(d) => GeneratorSimplifiedType(map(d)),
GeneratorWitnessSimplifiedType(n) => GeneratorWitnessSimplifiedType(n),
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/ty/item_path.rs
Expand Up @@ -479,7 +479,7 @@ pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option<DefId> {
match ty.sty {
ty::Adt(adt_def, _) => Some(adt_def.did),

ty::Dynamic(data, ..) => Some(data.principal().def_id()),
ty::Dynamic(data, ..) => data.principal_def_id(),

ty::Array(subty, _) |
ty::Slice(subty) => characteristic_def_id_of_type(subty),
Expand Down
21 changes: 16 additions & 5 deletions src/librustc/ty/sty.rs
Expand Up @@ -569,13 +569,18 @@ impl<'a, 'gcx, 'tcx> Binder<ExistentialPredicate<'tcx>> {
impl<'tcx> serialize::UseSpecializedDecodable for &'tcx List<ExistentialPredicate<'tcx>> {}

impl<'tcx> List<ExistentialPredicate<'tcx>> {
pub fn principal(&self) -> ExistentialTraitRef<'tcx> {
pub fn principal(&self) -> Option<ExistentialTraitRef<'tcx>> {
match self[0] {
ExistentialPredicate::Trait(tr) => tr,
ExistentialPredicate::Trait(tr) => Some(tr),
other => bug!("first predicate is {:?}", other),
}
}


pub fn principal_def_id(&self) -> Option<DefId> {
self.principal().map(|d| d.def_id)
}

#[inline]
pub fn projection_bounds<'a>(&'a self) ->
impl Iterator<Item=ExistentialProjection<'tcx>> + 'a {
Expand All @@ -599,8 +604,12 @@ impl<'tcx> List<ExistentialPredicate<'tcx>> {
}

impl<'tcx> Binder<&'tcx List<ExistentialPredicate<'tcx>>> {
pub fn principal(&self) -> PolyExistentialTraitRef<'tcx> {
Binder::bind(self.skip_binder().principal())
pub fn principal(&self) -> Option<ty::Binder<ExistentialTraitRef<'tcx>>> {
self.skip_binder().principal().map(Binder::bind)
}

pub fn principal_def_id(&self) -> Option<DefId> {
self.skip_binder().principal_def_id()
}

#[inline]
Expand Down Expand Up @@ -1917,7 +1926,9 @@ impl<'a, 'gcx, 'tcx> TyS<'tcx> {
}
Dynamic(ref obj, region) => {
out.push(region);
out.extend(obj.principal().skip_binder().substs.regions());
if let Some(principal) = obj.principal() {
out.extend(principal.skip_binder().substs.regions());
}
}
Adt(_, substs) | Opaque(_, substs) => {
out.extend(substs.regions())
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/ty/wf.rs
Expand Up @@ -384,7 +384,7 @@ impl<'a, 'gcx, 'tcx> WfPredicates<'a, 'gcx, 'tcx> {

let cause = self.cause(traits::MiscObligation);
let component_traits =
data.auto_traits().chain(once(data.principal().def_id()));
data.auto_traits().chain(data.principal_def_id());
self.out.extend(
component_traits.map(|did| traits::Obligation::new(
cause.clone(),
Expand Down
22 changes: 12 additions & 10 deletions src/librustc/util/ppaux.rs
Expand Up @@ -713,16 +713,18 @@ define_print! {
// Use a type that can't appear in defaults of type parameters.
let dummy_self = tcx.mk_infer(ty::FreshTy(0));

let principal = tcx
.lift(&self.principal())
.expect("could not lift TraitRef for printing")
.with_self_ty(tcx, dummy_self);
let projections = self.projection_bounds().map(|p| {
tcx.lift(&p)
.expect("could not lift projection for printing")
.with_self_ty(tcx, dummy_self)
}).collect::<Vec<_>>();
cx.parameterized(f, principal.substs, principal.def_id, &projections)?;
if let Some(principal) = self.principal() {
let principal = tcx
.lift(&principal)
.expect("could not lift TraitRef for printing")
.with_self_ty(tcx, dummy_self);
let projections = self.projection_bounds().map(|p| {
tcx.lift(&p)
.expect("could not lift projection for printing")
.with_self_ty(tcx, dummy_self)
}).collect::<Vec<_>>();
cx.parameterized(f, principal.substs, principal.def_id, &projections)?;
}

// Builtin bounds.
for did in self.auto_traits() {
Expand Down
5 changes: 3 additions & 2 deletions src/librustc_codegen_llvm/context.rs
Expand Up @@ -50,7 +50,8 @@ pub struct CodegenCx<'ll, 'tcx: 'll> {
/// Cache instances of monomorphic and polymorphic items
pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
/// Cache generated vtables
pub vtables: RefCell<FxHashMap<(Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>), &'ll Value>>,
pub vtables: RefCell<FxHashMap<
(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), &'ll Value>>,
/// Cache of constant strings,
pub const_cstr_cache: RefCell<FxHashMap<LocalInternedString, &'ll Value>>,

Expand Down Expand Up @@ -311,7 +312,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {

impl MiscMethods<'tcx> for CodegenCx<'ll, 'tcx> {
fn vtables(&self) -> &RefCell<FxHashMap<(Ty<'tcx>,
ty::PolyExistentialTraitRef<'tcx>), &'ll Value>>
Option<ty::PolyExistentialTraitRef<'tcx>>), &'ll Value>>
{
&self.vtables
}
Expand Down
3 changes: 2 additions & 1 deletion src/librustc_codegen_llvm/debuginfo/metadata.rs
Expand Up @@ -429,7 +429,8 @@ fn trait_pointer_metadata(
// But it does not describe the trait's methods.

let containing_scope = match trait_type.sty {
ty::Dynamic(ref data, ..) => Some(get_namespace_for_item(cx, data.principal().def_id())),
ty::Dynamic(ref data, ..) =>
data.principal_def_id().map(|did| get_namespace_for_item(cx, did)),
_ => {
bug!("debuginfo: Unexpected trait-object type in \
trait_pointer_metadata(): {:?}",
Expand Down
16 changes: 10 additions & 6 deletions src/librustc_codegen_llvm/debuginfo/type_names.rs
Expand Up @@ -107,12 +107,16 @@ pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
}
},
ty::Dynamic(ref trait_data, ..) => {
let principal = cx.tcx.normalize_erasing_late_bound_regions(
ty::ParamEnv::reveal_all(),
&trait_data.principal(),
);
push_item_name(cx, principal.def_id, false, output);
push_type_params(cx, principal.substs, output);
if let Some(principal) = trait_data.principal() {
let principal = cx.tcx.normalize_erasing_late_bound_regions(
ty::ParamEnv::reveal_all(),
&principal,
);
push_item_name(cx, principal.def_id, false, output);
push_type_params(cx, principal.substs, output);
} else {
output.push_str("dyn '_");
}
},
ty::FnDef(..) | ty::FnPtr(_) => {
let sig = t.fn_sig(cx.tcx);
Expand Down
13 changes: 10 additions & 3 deletions src/librustc_codegen_ssa/meth.rs
Expand Up @@ -69,7 +69,7 @@ impl<'a, 'tcx: 'a> VirtualIndex {
pub fn get_vtable<'tcx, Cx: CodegenMethods<'tcx>>(
cx: &Cx,
ty: Ty<'tcx>,
trait_ref: ty::PolyExistentialTraitRef<'tcx>,
trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
) -> Cx::Value {
let tcx = cx.tcx();

Expand All @@ -83,8 +83,15 @@ pub fn get_vtable<'tcx, Cx: CodegenMethods<'tcx>>(
// Not in the cache. Build it.
let nullptr = cx.const_null(cx.type_i8p());

let methods = tcx.vtable_methods(trait_ref.with_self_ty(tcx, ty));
let methods = methods.iter().cloned().map(|opt_mth| {
let methods_root;
let methods = if let Some(trait_ref) = trait_ref {
methods_root = tcx.vtable_methods(trait_ref.with_self_ty(tcx, ty));
methods_root.iter()
} else {
(&[]).iter()
};

let methods = methods.cloned().map(|opt_mth| {
opt_mth.map_or(nullptr, |(def_id, substs)| {
callee::resolve_and_get_fn_for_vtable(cx, def_id, substs)
})
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_ssa/traits/misc.rs
Expand Up @@ -11,7 +11,7 @@ use std::sync::Arc;
pub trait MiscMethods<'tcx>: BackendTypes {
fn vtables(
&self,
) -> &RefCell<FxHashMap<(Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>), Self::Value>>;
) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Self::Value>>;
fn check_overflow(&self) -> bool;
fn instances(&self) -> &RefCell<FxHashMap<Instance<'tcx>, Self::Value>>;
fn get_fn(&self, instance: Instance<'tcx>) -> Self::Value;
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/interpret/eval_context.rs
Expand Up @@ -42,7 +42,7 @@ pub struct EvalContext<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,

/// A cache for deduplicating vtables
pub(super) vtables: FxHashMap<(Ty<'tcx>, ty::PolyExistentialTraitRef<'tcx>), AllocId>,
pub(super) vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), AllocId>,
}

/// A stack frame.
Expand Down
13 changes: 9 additions & 4 deletions src/librustc_mir/interpret/traits.rs
@@ -1,3 +1,4 @@
use rustc_data_structures::sync::Lrc;
use rustc::ty::{self, Ty};
use rustc::ty::layout::{Size, Align, LayoutOf};
use rustc::mir::interpret::{Scalar, Pointer, EvalResult, PointerArithmetic};
Expand All @@ -14,7 +15,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M>
pub fn get_vtable(
&mut self,
ty: Ty<'tcx>,
poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
trace!("get_vtable(trait_ref={:?})", poly_trait_ref);

Expand All @@ -24,10 +25,14 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M>
return Ok(Pointer::from(vtable).with_default_tag());
}

let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
let trait_ref = self.tcx.erase_regions(&trait_ref);
let methods = if let Some(poly_trait_ref) = poly_trait_ref {
let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
let trait_ref = self.tcx.erase_regions(&trait_ref);

let methods = self.tcx.vtable_methods(trait_ref);
self.tcx.vtable_methods(trait_ref)
} else {
Lrc::new(Vec::new())
};

let layout = self.layout_of(ty)?;
assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
Expand Down
23 changes: 13 additions & 10 deletions src/librustc_mir/monomorphize/collector.rs
Expand Up @@ -894,20 +894,23 @@ fn create_mono_items_for_vtable_methods<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
!impl_ty.needs_subst() && !impl_ty.has_escaping_bound_vars());

if let ty::Dynamic(ref trait_ty, ..) = trait_ty.sty {
let poly_trait_ref = trait_ty.principal().with_self_ty(tcx, impl_ty);
assert!(!poly_trait_ref.has_escaping_bound_vars());

// Walk all methods of the trait, including those of its supertraits
let methods = tcx.vtable_methods(poly_trait_ref);
let methods = methods.iter().cloned().filter_map(|method| method)
.map(|(def_id, substs)| ty::Instance::resolve_for_vtable(
if let Some(principal) = trait_ty.principal() {
let poly_trait_ref = principal.with_self_ty(tcx, impl_ty);
assert!(!poly_trait_ref.has_escaping_bound_vars());

// Walk all methods of the trait, including those of its supertraits
let methods = tcx.vtable_methods(poly_trait_ref);
let methods = methods.iter().cloned().filter_map(|method| method)
.map(|(def_id, substs)| ty::Instance::resolve_for_vtable(
tcx,
ty::ParamEnv::reveal_all(),
def_id,
substs).unwrap())
.filter(|&instance| should_monomorphize_locally(tcx, &instance))
.map(|instance| create_fn_mono_item(instance));
output.extend(methods);
.filter(|&instance| should_monomorphize_locally(tcx, &instance))
.map(|instance| create_fn_mono_item(instance));
output.extend(methods);
}

// Also add the destructor
visit_drop_use(tcx, impl_ty, false, output);
}
Expand Down
17 changes: 10 additions & 7 deletions src/librustc_mir/monomorphize/item.rs
Expand Up @@ -304,13 +304,16 @@ impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
output.push(']');
},
ty::Dynamic(ref trait_data, ..) => {
let principal = trait_data.principal();
self.push_def_path(principal.def_id(), output);
self.push_type_params(
principal.skip_binder().substs,
trait_data.projection_bounds(),
output,
);
if let Some(principal) = trait_data.principal() {
self.push_def_path(principal.def_id(), output);
self.push_type_params(
principal.skip_binder().substs,
trait_data.projection_bounds(),
output,
);
} else {
output.push_str("dyn '_");
}
},
ty::Foreign(did) => self.push_def_path(did, output),
ty::FnDef(..) |
Expand Down

0 comments on commit 3aa1503

Please sign in to comment.