Auto merge of #119934 - compiler-errors:could-impl, r=jackh726

Make `InferCtxtExt::could_impl_trait` more precise, less ICEy

The implementation for `InferCtxtExt::could_impl_trait` was very wrong. Along with being pretty poorly named, way too specific to ADTs, it was also doing impl substitution wrong -- this caused an ICE (#119915).

This PR generalizes that code, gives it a clearer name, makes it stop using the new trait solver (lol), and fixes some fallout bad suggestions that are made worse with the code fix.

Fixes #119915
This commit is contained in:
bors 2024-01-14 06:37:15 +00:00
commit 0dab65b8a1
15 changed files with 128 additions and 101 deletions

View file

@ -1178,9 +1178,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} else { } else {
vec![(move_span.shrink_to_hi(), ".clone()".to_string())] vec![(move_span.shrink_to_hi(), ".clone()".to_string())]
}; };
if let Some(errors) = if let Some(errors) = self.infcx.type_implements_trait_shallow(
self.infcx.could_impl_trait(clone_trait, ty, self.param_env) clone_trait,
&& !has_sugg ty,
self.param_env,
) && !has_sugg
{ {
let msg = match &errors[..] { let msg = match &errors[..] {
[] => "you can `clone` the value and consume it, but this \ [] => "you can `clone` the value and consume it, but this \

View file

@ -1217,19 +1217,22 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
{ {
match self match self
.infcx .infcx
.could_impl_trait(clone_trait, ty.peel_refs(), self.param_env) .type_implements_trait_shallow(
clone_trait,
ty.peel_refs(),
self.param_env,
)
.as_deref() .as_deref()
{ {
Some([]) => { Some([]) => {
// The type implements Clone. // FIXME: This error message isn't useful, since we're just
err.span_help( // vaguely suggesting to clone a value that already
expr.span, // implements `Clone`.
format!( //
"you can `clone` the `{}` value and consume it, but this \ // A correct suggestion here would take into account the fact
might not be your desired behavior", // that inference may be affected by missing types on bindings,
ty.peel_refs(), // etc., to improve "tests/ui/borrowck/issue-91206.stderr", for
), // example.
);
} }
None => { None => {
if let hir::ExprKind::MethodCall(segment, _rcvr, [], span) = if let hir::ExprKind::MethodCall(segment, _rcvr, [], span) =

View file

@ -1623,7 +1623,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
); );
} else { } else {
if let Some(errors) = if let Some(errors) =
self.could_impl_trait(clone_trait_did, expected_ty, self.param_env) self.type_implements_trait_shallow(clone_trait_did, expected_ty, self.param_env)
{ {
match &errors[..] { match &errors[..] {
[] => {} [] => {}

View file

@ -1,13 +1,14 @@
use crate::solve::FulfillmentCtxt;
use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
use crate::traits::{self, DefiningAnchor, ObligationCtxt}; use crate::traits::{self, DefiningAnchor, ObligationCtxt, SelectionContext};
use crate::traits::TraitEngineExt as _;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::lang_items::LangItem; use rustc_hir::lang_items::LangItem;
use rustc_infer::traits::{TraitEngine, TraitEngineExt}; use rustc_infer::traits::{Obligation, TraitEngine, TraitEngineExt as _};
use rustc_middle::arena::ArenaAllocatable; use rustc_middle::arena::ArenaAllocatable;
use rustc_middle::infer::canonical::{Canonical, CanonicalQueryResponse, QueryResponse}; use rustc_middle::infer::canonical::{Canonical, CanonicalQueryResponse, QueryResponse};
use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::query::NoSolution;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitableExt};
use rustc_middle::ty::{GenericArg, ToPredicate}; use rustc_middle::ty::{GenericArg, ToPredicate};
use rustc_span::DUMMY_SP; use rustc_span::DUMMY_SP;
@ -21,7 +22,8 @@ pub trait InferCtxtExt<'tcx> {
fn type_is_sized_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool; fn type_is_sized_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool;
/// Check whether a `ty` implements given trait(trait_def_id). /// Check whether a `ty` implements given trait(trait_def_id) without side-effects.
///
/// The inputs are: /// The inputs are:
/// ///
/// - the def-id of the trait /// - the def-id of the trait
@ -29,8 +31,8 @@ pub trait InferCtxtExt<'tcx> {
/// - the parameter environment /// - the parameter environment
/// ///
/// Invokes `evaluate_obligation`, so in the event that evaluating /// Invokes `evaluate_obligation`, so in the event that evaluating
/// `Ty: Trait` causes overflow, EvaluatedToErrStackDependent (or EvaluatedToAmbigStackDependent) /// `Ty: Trait` causes overflow, EvaluatedToErrStackDependent
/// will be returned. /// (or EvaluatedToAmbigStackDependent) will be returned.
fn type_implements_trait( fn type_implements_trait(
&self, &self,
trait_def_id: DefId, trait_def_id: DefId,
@ -38,7 +40,18 @@ pub trait InferCtxtExt<'tcx> {
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
) -> traits::EvaluationResult; ) -> traits::EvaluationResult;
fn could_impl_trait( /// Returns `Some` if a type implements a trait shallowly, without side-effects,
/// along with any errors that would have been reported upon further obligation
/// processing.
///
/// - If this returns `Some([])`, then the trait holds modulo regions.
/// - If this returns `Some([errors..])`, then the trait has an impl for
/// the self type, but some nested obligations do not hold.
/// - If this returns `None`, no implementation that applies could be found.
///
/// FIXME(-Znext-solver): Due to the recursive nature of the new solver,
/// this will probably only ever return `Some([])` or `None`.
fn type_implements_trait_shallow(
&self, &self,
trait_def_id: DefId, trait_def_id: DefId,
ty: Ty<'tcx>, ty: Ty<'tcx>,
@ -86,64 +99,26 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
self.evaluate_obligation(&obligation).unwrap_or(traits::EvaluationResult::EvaluatedToErr) self.evaluate_obligation(&obligation).unwrap_or(traits::EvaluationResult::EvaluatedToErr)
} }
fn could_impl_trait( fn type_implements_trait_shallow(
&self, &self,
trait_def_id: DefId, trait_def_id: DefId,
ty: Ty<'tcx>, ty: Ty<'tcx>,
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
) -> Option<Vec<traits::FulfillmentError<'tcx>>> { ) -> Option<Vec<traits::FulfillmentError<'tcx>>> {
self.probe(|_snapshot| { self.probe(|_snapshot| {
if let ty::Adt(def, args) = ty.kind() let mut selcx = SelectionContext::new(self);
&& let Some((impl_def_id, _)) = self match selcx.select(&Obligation::new(
.tcx self.tcx,
.all_impls(trait_def_id) ObligationCause::dummy(),
.filter_map(|impl_def_id| { param_env,
self.tcx.impl_trait_ref(impl_def_id).map(|r| (impl_def_id, r)) ty::TraitRef::new(self.tcx, trait_def_id, [ty]),
}) )) {
.map(|(impl_def_id, imp)| (impl_def_id, imp.skip_binder())) Ok(Some(selection)) => {
.find(|(_, imp)| match imp.self_ty().peel_refs().kind() { let mut fulfill_cx = <dyn TraitEngine<'tcx>>::new(self);
ty::Adt(i_def, _) if i_def.did() == def.did() => true, fulfill_cx.register_predicate_obligations(self, selection.nested_obligations());
_ => false, Some(fulfill_cx.select_all_or_error(self))
})
{
let mut fulfill_cx = FulfillmentCtxt::new(self);
// We get all obligations from the impl to talk about specific
// trait bounds.
let obligations = self
.tcx
.predicates_of(impl_def_id)
.instantiate(self.tcx, args)
.into_iter()
.map(|(clause, span)| {
traits::Obligation::new(
self.tcx,
traits::ObligationCause::dummy_with_span(span),
param_env,
clause,
)
})
.collect::<Vec<_>>();
fulfill_cx.register_predicate_obligations(self, obligations);
let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty]);
let obligation = traits::Obligation::new(
self.tcx,
traits::ObligationCause::dummy(),
param_env,
trait_ref,
);
fulfill_cx.register_predicate_obligation(self, obligation);
let mut errors = fulfill_cx.select_all_or_error(self);
// We remove the last predicate failure, which corresponds to
// the top-level obligation, because most of the type we only
// care about the other ones, *except* when it is the only one.
// This seems to only be relevant for arbitrary self-types.
// Look at `tests/ui/moves/move-fn-self-receiver.rs`.
if errors.len() > 1 {
errors.truncate(errors.len() - 1);
} }
Some(errors) Ok(None) | Err(_) => None,
} else {
None
} }
}) })
} }

View file

@ -36,6 +36,11 @@ pub struct FulfillmentCtxt<'tcx> {
impl<'tcx> FulfillmentCtxt<'tcx> { impl<'tcx> FulfillmentCtxt<'tcx> {
pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx> { pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx> {
assert!(
infcx.next_trait_solver(),
"new trait solver fulfillment context created when \
infcx is set up for old trait solver"
);
FulfillmentCtxt { obligations: Vec::new(), usable_in_snapshot: infcx.num_open_snapshots() } FulfillmentCtxt { obligations: Vec::new(), usable_in_snapshot: infcx.num_open_snapshots() }
} }
} }

View file

@ -80,6 +80,11 @@ static_assert_size!(PendingPredicateObligation<'_>, 72);
impl<'tcx> FulfillmentContext<'tcx> { impl<'tcx> FulfillmentContext<'tcx> {
/// Creates a new fulfillment context. /// Creates a new fulfillment context.
pub(super) fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentContext<'tcx> { pub(super) fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentContext<'tcx> {
assert!(
!infcx.next_trait_solver(),
"old trait solver fulfillment context created when \
infcx is set up for new trait solver"
);
FulfillmentContext { FulfillmentContext {
predicates: ObligationForest::new(), predicates: ObligationForest::new(),
usable_in_snapshot: infcx.num_open_snapshots(), usable_in_snapshot: infcx.num_open_snapshots(),

View file

@ -0,0 +1,28 @@
use std::marker::PhantomData;
struct Example<E, FakeParam>(PhantomData<(fn(E), fn(FakeParam))>);
struct NoLifetime;
struct Immutable<'a>(PhantomData<&'a ()>);
impl<'a, E: 'a> Copy for Example<E, Immutable<'a>> {}
impl<'a, E: 'a> Clone for Example<E, Immutable<'a>> {
fn clone(&self) -> Self {
*self
}
}
impl<E, FakeParam> Example<E, FakeParam> {
unsafe fn change<NewFakeParam>(self) -> Example<E, NewFakeParam> {
Example(PhantomData)
}
}
impl<E> Example<E, NoLifetime> {
fn the_ice(&mut self) -> Example<E, Immutable<'_>> {
unsafe { self.change() }
//~^ ERROR cannot move out of `*self` which is behind a mutable reference
}
}
fn main() {}

View file

@ -0,0 +1,17 @@
error[E0507]: cannot move out of `*self` which is behind a mutable reference
--> $DIR/issue-119915-bad-clone-suggestion.rs:23:18
|
LL | unsafe { self.change() }
| ^^^^ -------- `*self` moved due to this method call
| |
| move occurs because `*self` has type `Example<E, NoLifetime>`, which does not implement the `Copy` trait
|
note: `Example::<E, FakeParam>::change` takes ownership of the receiver `self`, which moves `*self`
--> $DIR/issue-119915-bad-clone-suggestion.rs:16:36
|
LL | unsafe fn change<NewFakeParam>(self) -> Example<E, NewFakeParam> {
| ^^^^
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0507`.

View file

@ -3,7 +3,6 @@ fn main() {
let mut test = Vec::new(); let mut test = Vec::new();
let rofl: &Vec<Vec<i32>> = &mut test; let rofl: &Vec<Vec<i32>> = &mut test;
//~^ HELP consider changing this binding's type //~^ HELP consider changing this binding's type
//~| HELP you can `clone` the `Vec<Vec<i32>>` value and consume it, but this might not be your desired behavior
rofl.push(Vec::new()); rofl.push(Vec::new());
//~^ ERROR cannot borrow `*rofl` as mutable, as it is behind a `&` reference //~^ ERROR cannot borrow `*rofl` as mutable, as it is behind a `&` reference
//~| NOTE `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable //~| NOTE `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable

View file

@ -1,21 +1,16 @@
error[E0596]: cannot borrow `*rofl` as mutable, as it is behind a `&` reference error[E0596]: cannot borrow `*rofl` as mutable, as it is behind a `&` reference
--> $DIR/issue-85765-closure.rs:7:9 --> $DIR/issue-85765-closure.rs:6:9
| |
LL | rofl.push(Vec::new()); LL | rofl.push(Vec::new());
| ^^^^ `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable | ^^^^ `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable
| |
help: you can `clone` the `Vec<Vec<i32>>` value and consume it, but this might not be your desired behavior
--> $DIR/issue-85765-closure.rs:4:36
|
LL | let rofl: &Vec<Vec<i32>> = &mut test;
| ^^^^^^^^^
help: consider changing this binding's type help: consider changing this binding's type
| |
LL | let rofl: &mut Vec<Vec<i32>> = &mut test; LL | let rofl: &mut Vec<Vec<i32>> = &mut test;
| ~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~
error[E0594]: cannot assign to `*r`, which is behind a `&` reference error[E0594]: cannot assign to `*r`, which is behind a `&` reference
--> $DIR/issue-85765-closure.rs:14:9 --> $DIR/issue-85765-closure.rs:13:9
| |
LL | *r = 0; LL | *r = 0;
| ^^^^^^ `r` is a `&` reference, so the data it refers to cannot be written | ^^^^^^ `r` is a `&` reference, so the data it refers to cannot be written
@ -26,7 +21,7 @@ LL | let r = &mut mutvar;
| +++ | +++
error[E0594]: cannot assign to `*x`, which is behind a `&` reference error[E0594]: cannot assign to `*x`, which is behind a `&` reference
--> $DIR/issue-85765-closure.rs:21:9 --> $DIR/issue-85765-closure.rs:20:9
| |
LL | *x = 1; LL | *x = 1;
| ^^^^^^ `x` is a `&` reference, so the data it refers to cannot be written | ^^^^^^ `x` is a `&` reference, so the data it refers to cannot be written
@ -37,7 +32,7 @@ LL | let x: &mut usize = &mut{0};
| ~~~~~~~~~~ | ~~~~~~~~~~
error[E0594]: cannot assign to `*y`, which is behind a `&` reference error[E0594]: cannot assign to `*y`, which is behind a `&` reference
--> $DIR/issue-85765-closure.rs:28:9 --> $DIR/issue-85765-closure.rs:27:9
| |
LL | *y = 1; LL | *y = 1;
| ^^^^^^ `y` is a `&` reference, so the data it refers to cannot be written | ^^^^^^ `y` is a `&` reference, so the data it refers to cannot be written

View file

@ -2,7 +2,6 @@ fn main() {
let mut test = Vec::new(); let mut test = Vec::new();
let rofl: &Vec<Vec<i32>> = &mut test; let rofl: &Vec<Vec<i32>> = &mut test;
//~^ HELP consider changing this binding's type //~^ HELP consider changing this binding's type
//~| HELP you can `clone` the `Vec<Vec<i32>>` value and consume it, but this might not be your desired behavior
rofl.push(Vec::new()); rofl.push(Vec::new());
//~^ ERROR cannot borrow `*rofl` as mutable, as it is behind a `&` reference //~^ ERROR cannot borrow `*rofl` as mutable, as it is behind a `&` reference
//~| NOTE `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable //~| NOTE `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable

View file

@ -1,21 +1,16 @@
error[E0596]: cannot borrow `*rofl` as mutable, as it is behind a `&` reference error[E0596]: cannot borrow `*rofl` as mutable, as it is behind a `&` reference
--> $DIR/issue-85765.rs:6:5 --> $DIR/issue-85765.rs:5:5
| |
LL | rofl.push(Vec::new()); LL | rofl.push(Vec::new());
| ^^^^ `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable | ^^^^ `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable
| |
help: you can `clone` the `Vec<Vec<i32>>` value and consume it, but this might not be your desired behavior
--> $DIR/issue-85765.rs:3:32
|
LL | let rofl: &Vec<Vec<i32>> = &mut test;
| ^^^^^^^^^
help: consider changing this binding's type help: consider changing this binding's type
| |
LL | let rofl: &mut Vec<Vec<i32>> = &mut test; LL | let rofl: &mut Vec<Vec<i32>> = &mut test;
| ~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~
error[E0594]: cannot assign to `*r`, which is behind a `&` reference error[E0594]: cannot assign to `*r`, which is behind a `&` reference
--> $DIR/issue-85765.rs:13:5 --> $DIR/issue-85765.rs:12:5
| |
LL | *r = 0; LL | *r = 0;
| ^^^^^^ `r` is a `&` reference, so the data it refers to cannot be written | ^^^^^^ `r` is a `&` reference, so the data it refers to cannot be written
@ -26,7 +21,7 @@ LL | let r = &mut mutvar;
| +++ | +++
error[E0594]: cannot assign to `*x`, which is behind a `&` reference error[E0594]: cannot assign to `*x`, which is behind a `&` reference
--> $DIR/issue-85765.rs:20:5 --> $DIR/issue-85765.rs:19:5
| |
LL | *x = 1; LL | *x = 1;
| ^^^^^^ `x` is a `&` reference, so the data it refers to cannot be written | ^^^^^^ `x` is a `&` reference, so the data it refers to cannot be written
@ -37,7 +32,7 @@ LL | let x: &mut usize = &mut{0};
| ~~~~~~~~~~ | ~~~~~~~~~~
error[E0594]: cannot assign to `*y`, which is behind a `&` reference error[E0594]: cannot assign to `*y`, which is behind a `&` reference
--> $DIR/issue-85765.rs:27:5 --> $DIR/issue-85765.rs:26:5
| |
LL | *y = 1; LL | *y = 1;
| ^^^^^^ `y` is a `&` reference, so the data it refers to cannot be written | ^^^^^^ `y` is a `&` reference, so the data it refers to cannot be written

View file

@ -10,7 +10,6 @@ fn main() {
let client = TestClient; let client = TestClient;
let inner = client.get_inner_ref(); let inner = client.get_inner_ref();
//~^ HELP consider specifying this binding's type //~^ HELP consider specifying this binding's type
//~| HELP you can `clone` the `Vec<usize>` value and consume it, but this might not be your desired behavior
inner.clear(); inner.clear();
//~^ ERROR cannot borrow `*inner` as mutable, as it is behind a `&` reference [E0596] //~^ ERROR cannot borrow `*inner` as mutable, as it is behind a `&` reference [E0596]
//~| NOTE `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable //~| NOTE `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable

View file

@ -1,14 +1,9 @@
error[E0596]: cannot borrow `*inner` as mutable, as it is behind a `&` reference error[E0596]: cannot borrow `*inner` as mutable, as it is behind a `&` reference
--> $DIR/issue-91206.rs:14:5 --> $DIR/issue-91206.rs:13:5
| |
LL | inner.clear(); LL | inner.clear();
| ^^^^^ `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable | ^^^^^ `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable
| |
help: you can `clone` the `Vec<usize>` value and consume it, but this might not be your desired behavior
--> $DIR/issue-91206.rs:11:17
|
LL | let inner = client.get_inner_ref();
| ^^^^^^^^^^^^^^^^^^^^^^
help: consider specifying this binding's type help: consider specifying this binding's type
| |
LL | let inner: &mut Vec<usize> = client.get_inner_ref(); LL | let inner: &mut Vec<usize> = client.get_inner_ref();

View file

@ -55,10 +55,15 @@ note: `Foo::use_box_self` takes ownership of the receiver `self`, which moves `b
| |
LL | fn use_box_self(self: Box<Self>) {} LL | fn use_box_self(self: Box<Self>) {}
| ^^^^ | ^^^^
help: you could `clone` the value and consume it, if the `Box<Foo>: Clone` trait bound could be satisfied help: you could `clone` the value and consume it, if the `Foo: Clone` trait bound could be satisfied
| |
LL | boxed_foo.clone().use_box_self(); LL | boxed_foo.clone().use_box_self();
| ++++++++ | ++++++++
help: consider annotating `Foo` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
LL | struct Foo;
|
error[E0382]: use of moved value: `pin_box_foo` error[E0382]: use of moved value: `pin_box_foo`
--> $DIR/move-fn-self-receiver.rs:46:5 --> $DIR/move-fn-self-receiver.rs:46:5
@ -75,10 +80,15 @@ note: `Foo::use_pin_box_self` takes ownership of the receiver `self`, which move
| |
LL | fn use_pin_box_self(self: Pin<Box<Self>>) {} LL | fn use_pin_box_self(self: Pin<Box<Self>>) {}
| ^^^^ | ^^^^
help: you could `clone` the value and consume it, if the `Box<Foo>: Clone` trait bound could be satisfied help: you could `clone` the value and consume it, if the `Foo: Clone` trait bound could be satisfied
| |
LL | pin_box_foo.clone().use_pin_box_self(); LL | pin_box_foo.clone().use_pin_box_self();
| ++++++++ | ++++++++
help: consider annotating `Foo` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
LL | struct Foo;
|
error[E0505]: cannot move out of `mut_foo` because it is borrowed error[E0505]: cannot move out of `mut_foo` because it is borrowed
--> $DIR/move-fn-self-receiver.rs:50:5 --> $DIR/move-fn-self-receiver.rs:50:5