Skip to content

Commit

Permalink
Harden Ty constructors a bit in debug mode
Browse files Browse the repository at this point in the history
`Ty::new` wasn't used anywhere outside this module

`Ty::new_adt` shouldn't ever be used for anything but adts. This hasn't caught any bugs, but seems good to check anyway
  • Loading branch information
oli-obk committed Jan 9, 2025
1 parent 65d7296 commit 91b6b4e
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ impl<'tcx> Ty<'tcx> {
/// The more specific methods will often optimize their creation.
#[allow(rustc::usage_of_ty_tykind)]
#[inline]
pub fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
tcx.mk_ty_from_kind(st)
}

Expand Down Expand Up @@ -613,6 +613,41 @@ impl<'tcx> Ty<'tcx> {
#[inline]
pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
tcx.debug_assert_args_compatible(def.did(), args);
if cfg!(debug_assertions) {
match tcx.def_kind(def.did()) {
DefKind::Struct | DefKind::Union | DefKind::Enum => {}
DefKind::Mod
| DefKind::Variant
| DefKind::Trait
| DefKind::TyAlias
| DefKind::ForeignTy
| DefKind::TraitAlias
| DefKind::AssocTy
| DefKind::TyParam
| DefKind::Fn
| DefKind::Const
| DefKind::ConstParam
| DefKind::Static { .. }
| DefKind::Ctor(..)
| DefKind::AssocFn
| DefKind::AssocConst
| DefKind::Macro(..)
| DefKind::ExternCrate
| DefKind::Use
| DefKind::ForeignMod
| DefKind::AnonConst
| DefKind::InlineConst
| DefKind::OpaqueTy
| DefKind::Field
| DefKind::LifetimeParam
| DefKind::GlobalAsm
| DefKind::Impl { .. }
| DefKind::Closure
| DefKind::SyntheticCoroutineBody => {
bug!("not an adt: {def:?} ({:?})", tcx.def_kind(def.did()))
}
}
}
Ty::new(tcx, Adt(def, args))
}

Expand Down Expand Up @@ -772,7 +807,7 @@ impl<'tcx> Ty<'tcx> {
}
}
});
Ty::new(tcx, Adt(adt_def, args))
Ty::new_adt(tcx, adt_def, args)
}

#[inline]
Expand Down

0 comments on commit 91b6b4e

Please sign in to comment.