Skip to content

Commit

Permalink
[perf] Skip attempting to run coerce_unsized on an inference variable
Browse files Browse the repository at this point in the history
See the included comment for a detailed explanation of why this is
sound.
  • Loading branch information
Aaron1011 committed Feb 27, 2020
1 parent 6d69cab commit 32c360b
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/librustc_typeck/check/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,36 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
debug!("coerce_unsized(source={:?}, target={:?})", source, target);

// These 'if' statements require some explanation.
// The `CoerceUnsized` trait is special - it is only
// possible to write `impl CoerceUnsized<B> for A` where
// A and B have 'matching' fields. This rules out the following
// two types of blanket impls:
//
// `impl<T> CoerceUnsized<T> for SomeType`
// `impl<T> CoerceUnsized<SomeType> for T`
//
// Both of these trigger a special `CoerceUnsized`-related error (E0376)
//
// We can take advantage of this fact to avoid performing unecessary work.
// If either `source` or `target` is a type variable, then any applicable impl
// would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
// or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
// SomeType`).
//
// However, these are exactly the kinds of impls which are forbidden by
// the compiler! Therefore, we can be sure that coercion will always fail
// when either the source or target type is a type variable. This allows us
// to skip performing any trait selection, and immediately bail out.
if self.shallow_resolve(source).is_ty_var() {
debug!("coerce_unsized: source is a TyVar, bailing out");
return Err(TypeError::Mismatch);
}
if self.shallow_resolve(target).is_ty_var() {
debug!("coerce_unsized: target is a TyVar, bailing out");
return Err(TypeError::Mismatch);
}

let traits =
(self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
let (unsize_did, coerce_unsized_did) = if let (Some(u), Some(cu)) = traits {
Expand Down

0 comments on commit 32c360b

Please sign in to comment.