Skip to content

Commit

Permalink
Assert that we always construct dyn types with the right number of pr…
Browse files Browse the repository at this point in the history
…ojections
  • Loading branch information
compiler-errors committed Feb 21, 2025
1 parent 72bd174 commit a2a0cfe
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
3 changes: 3 additions & 0 deletions compiler/rustc_middle/src/ty/relate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ impl<'tcx> Relate<TyCtxt<'tcx>> for &'tcx ty::List<ty::PolyExistentialPredicate<
b: Self,
) -> RelateResult<'tcx, Self> {
let tcx = relation.cx();
// Fast path for when the auto traits do not match, or if the principals
// are from different traits and therefore the projections definitely don't
// match up.
if a.len() != b.len() {
return Err(TypeError::ExistentialMismatch(ExpectedFound::new(a, b)));
}
Expand Down
30 changes: 29 additions & 1 deletion compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, extension
use rustc_span::{DUMMY_SP, Span, Symbol, sym};
use rustc_type_ir::TyKind::*;
use rustc_type_ir::visit::TypeVisitableExt;
use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind};
use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind, elaborate};
use tracing::instrument;
use ty::util::{AsyncDropGlueMorphology, IntTypeExt};

Expand Down Expand Up @@ -720,6 +720,34 @@ impl<'tcx> Ty<'tcx> {
reg: ty::Region<'tcx>,
repr: DynKind,
) -> Ty<'tcx> {
if cfg!(debug_assertions) {
let projection_count = obj.projection_bounds().count();
let expected_count: usize = obj
.principal_def_id()
.into_iter()
.flat_map(|principal_def_id| {
// NOTE: This should agree with `needed_associated_types` in
// dyn trait lowering, or else we'll have ICEs.
elaborate::supertraits(
tcx,
ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
)
.map(|principal| {
tcx.associated_items(principal.def_id())
.in_definition_order()
.filter(|item| item.kind == ty::AssocKind::Type)
.filter(|item| !item.is_impl_trait_in_trait())
.filter(|item| !tcx.generics_require_sized_self(item.def_id))
.count()
})
})
.sum();
assert_eq!(
projection_count, expected_count,
"expected {obj:?} to have {expected_count} projections, \
but it has {projection_count}"
);
}
Ty::new(tcx, Dynamic(obj, reg, repr))
}

Expand Down

0 comments on commit a2a0cfe

Please sign in to comment.