Skip to content

Commit

Permalink
Special case inference around AsRef<Vec<T>> to support existing cod…
Browse files Browse the repository at this point in the history
…e without reverting rust-lang#95098

 rust-lang#95098 introduces new `From` impls for `Vec`, which can break existing
 code that relies on inference when calling `.as_ref()`. This change
 explicitly carves out a bias in the inference machinery to keep
 existing code compiling, while still maintaining the new `From` impls.

 Reported in rust-lang#96074.
  • Loading branch information
estebank committed Apr 26, 2022
1 parent 3d237ab commit b47bf81
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
19 changes: 18 additions & 1 deletion compiler/rustc_trait_selection/src/traits/select/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1767,7 +1767,24 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
!needs_infer
}
Some(_) => true,
None => false,
None => {
if let Some(other) = tcx.impl_trait_ref(other_def)
&& let Some(victim) = tcx.impl_trait_ref(victim_def)
&& tcx.is_diagnostic_item(sym::AsRef, other.def_id)
&& tcx.is_diagnostic_item(sym::AsRef, victim.def_id)
&& other.substs.len() > 1
&& victim.substs.len() > 1
&& let ty::Slice(other) = other.substs.type_at(1).kind()
&& let ty::Adt(def, substs) = victim.substs.type_at(1).kind()
&& tcx.is_diagnostic_item(sym::Vec, def.did())
{
// If this is an `AsRef` implementation that can go either way for
// `AsRef<[T]>` or `AsRef<Vec[T]>`, prefer the former.
other == &substs.type_at(0)
} else {
false
}
}
}
} else {
false
Expand Down
14 changes: 14 additions & 0 deletions src/test/ui/inference/vec-from-array-ref-impl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// check-pass

#[derive(Clone)]
struct Constraint;

fn constraints<C>(constraints: C)
where C: Into<Vec<Constraint>>
{
let _: Vec<Constraint> = constraints.into();
}

fn main() {
constraints(vec![Constraint].as_ref());
}

0 comments on commit b47bf81

Please sign in to comment.