Skip to content

Commit

Permalink
Add some extra information to opaque type cycle errors
Browse files Browse the repository at this point in the history
  • Loading branch information
oli-obk committed Jul 5, 2023
1 parent 66ae999 commit 9e98feb
Show file tree
Hide file tree
Showing 16 changed files with 421 additions and 24 deletions.
4 changes: 4 additions & 0 deletions compiler/rustc_middle/src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,10 @@ pub enum SelectionError<'tcx> {
/// Signaling that an error has already been emitted, to avoid
/// multiple errors being shown.
ErrorReporting,
/// Computing an opaque type's hidden type caused an error (e.g. a cycle error).
/// We can thus not know whether the hidden type implements an auto trait, so
/// we should not presume anything about it.
OpaqueTypeAutoTraitLeakageUnknown(DefId),
}

#[derive(Clone, Debug, TypeVisitable, Lift)]
Expand Down
46 changes: 45 additions & 1 deletion compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use rustc_infer::infer::error_reporting::TypeErrCtxt;
use rustc_infer::infer::{InferOk, TypeTrace};
use rustc_middle::traits::select::OverflowError;
use rustc_middle::traits::solve::Goal;
use rustc_middle::traits::SelectionOutputTypeParameterMismatch;
use rustc_middle::traits::{DefiningAnchor, SelectionOutputTypeParameterMismatch};
use rustc_middle::ty::abstract_const::NotConstEvaluatable;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable};
Expand Down Expand Up @@ -1152,6 +1152,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
}
}

SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id) => self.report_opaque_type_auto_trait_leakage(
&obligation,
def_id,
),

TraitNotObjectSafe(did) => {
let violations = self.tcx.object_safety_violations(did);
report_object_safety_error(self.tcx, span, did, violations)
Expand Down Expand Up @@ -1465,6 +1470,12 @@ trait InferCtxtPrivExt<'tcx> {
terr: TypeError<'tcx>,
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;

fn report_opaque_type_auto_trait_leakage(
&self,
obligation: &PredicateObligation<'tcx>,
def_id: DefId,
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>;

fn report_type_parameter_mismatch_error(
&self,
obligation: &PredicateObligation<'tcx>,
Expand Down Expand Up @@ -3186,6 +3197,39 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
)
}

fn report_opaque_type_auto_trait_leakage(
&self,
obligation: &PredicateObligation<'tcx>,
def_id: DefId,
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
let name = match self.tcx.opaque_type_origin(def_id.expect_local()) {
hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_) => {
format!("opaque type")
}
hir::OpaqueTyOrigin::TyAlias { .. } => {
format!("`{}`", self.tcx.def_path_debug_str(def_id))
}
};
let mut err = self.tcx.sess.struct_span_err(
obligation.cause.span,
format!("cannot check whether the hidden type of {name} satisfies auto traits"),
);
err.span_note(self.tcx.def_span(def_id), "opaque type is declared here");
match self.defining_use_anchor {
DefiningAnchor::Bubble | DefiningAnchor::Error => {}
DefiningAnchor::Bind(bind) => {
err.span_note(
self.tcx.def_ident_span(bind).unwrap_or_else(|| self.tcx.def_span(bind)),
"this item depends on auto traits of the hidden type, \
but may also be registering the hidden type. \
This is not supported right now. \
You can try moving the opaque type and the item that actually registers a hidden type into a new submodule".to_string(),
);
}
};
err
}

fn report_type_parameter_mismatch_error(
&self,
obligation: &PredicateObligation<'tcx>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
}

AutoImplCandidate => {
let data = self.confirm_auto_impl_candidate(obligation);
let data = self.confirm_auto_impl_candidate(obligation)?;
ImplSource::Builtin(data)
}

Expand Down Expand Up @@ -376,12 +376,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
fn confirm_auto_impl_candidate(
&mut self,
obligation: &TraitObligation<'tcx>,
) -> Vec<PredicateObligation<'tcx>> {
) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
debug!(?obligation, "confirm_auto_impl_candidate");

let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
let types = self.constituent_types_for_ty(self_ty);
self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types)
let types = self.constituent_types_for_ty(self_ty)?;
Ok(self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types))
}

/// See `confirm_auto_impl_candidate`.
Expand Down
12 changes: 8 additions & 4 deletions compiler/rustc_trait_selection/src/traits/select/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2294,8 +2294,8 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
fn constituent_types_for_ty(
&self,
t: ty::Binder<'tcx, Ty<'tcx>>,
) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
match *t.skip_binder().kind() {
) -> Result<ty::Binder<'tcx, Vec<Ty<'tcx>>>, SelectionError<'tcx>> {
Ok(match *t.skip_binder().kind() {
ty::Uint(_)
| ty::Int(_)
| ty::Bool
Expand Down Expand Up @@ -2359,12 +2359,16 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
}

ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
let ty = self.tcx().type_of(def_id);
if ty.skip_binder().references_error() {
return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id));
}
// We can resolve the `impl Trait` to its concrete type,
// which enforces a DAG between the functions requiring
// the auto trait bounds in question.
t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
t.rebind(vec![ty.subst(self.tcx(), substs)])
}
}
})
}

fn collect_predicates_for_types(
Expand Down
1 change: 1 addition & 0 deletions tests/ui/generator/layout-error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ fn main() {
type F = impl Future;
// Check that statics are inhabited computes they layout.
static POOL: Task<F> = Task::new();
//~^ ERROR: cannot check whether the hidden type of `layout_error[b009]::main::F::{opaque#0}` satisfies auto traits
Task::spawn(&POOL, || cb());
}
20 changes: 19 additions & 1 deletion tests/ui/generator/layout-error.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,24 @@ error[E0425]: cannot find value `Foo` in this scope
LL | let a = Foo;
| ^^^ not found in this scope

error: aborting due to previous error
error: cannot check whether the hidden type of `layout_error[b009]::main::F::{opaque#0}` satisfies auto traits
--> $DIR/layout-error.rs:26:18
|
LL | static POOL: Task<F> = Task::new();
| ^^^^^^^
|
note: opaque type is declared here
--> $DIR/layout-error.rs:24:14
|
LL | type F = impl Future;
| ^^^^^^^^^^^
note: required because it appears within the type `Task<F>`
--> $DIR/layout-error.rs:9:12
|
LL | pub struct Task<F: Future>(F);
| ^^^^
= note: shared static variables must have a type that implements `Sync`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0425`.
6 changes: 4 additions & 2 deletions tests/ui/impl-trait/auto-trait-leak.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,23 @@ use std::rc::Rc;

fn send<T: Send>(_: T) {}

fn main() {
}
fn main() {}

// Cycles should work as the deferred obligations are
// independently resolved and only require the concrete
// return type, which can't depend on the obligation.
fn cycle1() -> impl Clone {
//~^ ERROR cycle detected
//~| ERROR cycle detected
send(cycle2().clone());
//~^ ERROR: cannot check whether the hidden type of opaque type satisfies auto traits

Rc::new(Cell::new(5))
}

fn cycle2() -> impl Clone {
send(cycle1().clone());
//~^ ERROR: cannot check whether the hidden type of opaque type satisfies auto traits

Rc::new(String::from("foo"))
}
91 changes: 87 additions & 4 deletions tests/ui/impl-trait/auto-trait-leak.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error[E0391]: cycle detected when computing type of `cycle1::{opaque#0}`
--> $DIR/auto-trait-leak.rs:12:16
--> $DIR/auto-trait-leak.rs:11:16
|
LL | fn cycle1() -> impl Clone {
| ^^^^^^^^^^
Expand All @@ -11,12 +11,12 @@ LL | send(cycle2().clone());
| ^^^^
= note: ...which requires evaluating trait selection obligation `cycle2::{opaque#0}: core::marker::Send`...
note: ...which requires computing type of `cycle2::{opaque#0}`...
--> $DIR/auto-trait-leak.rs:19:16
--> $DIR/auto-trait-leak.rs:20:16
|
LL | fn cycle2() -> impl Clone {
| ^^^^^^^^^^
note: ...which requires type-checking `cycle2`...
--> $DIR/auto-trait-leak.rs:20:5
--> $DIR/auto-trait-leak.rs:21:5
|
LL | send(cycle1().clone());
| ^^^^
Expand All @@ -34,6 +34,89 @@ LL | | Rc::new(String::from("foo"))
LL | | }
| |_^

error: aborting due to previous error
error[E0391]: cycle detected when computing type of `cycle1::{opaque#0}`
--> $DIR/auto-trait-leak.rs:11:16
|
LL | fn cycle1() -> impl Clone {
| ^^^^^^^^^^
|
note: ...which requires type-checking `cycle1`...
--> $DIR/auto-trait-leak.rs:14:5
|
LL | send(cycle2().clone());
| ^^^^
= note: ...which requires evaluating trait selection obligation `cycle2::{opaque#0}: core::marker::Send`...
note: ...which requires computing type of `cycle2::{opaque#0}`...
--> $DIR/auto-trait-leak.rs:20:16
|
LL | fn cycle2() -> impl Clone {
| ^^^^^^^^^^
note: ...which requires type-checking `cycle2`...
--> $DIR/auto-trait-leak.rs:20:1
|
LL | fn cycle2() -> impl Clone {
| ^^^^^^^^^^^^^^^^^^^^^^^^^
= note: ...which again requires computing type of `cycle1::{opaque#0}`, completing the cycle
note: cycle used when checking item types in top-level module
--> $DIR/auto-trait-leak.rs:1:1
|
LL | / use std::cell::Cell;
LL | | use std::rc::Rc;
LL | |
LL | | fn send<T: Send>(_: T) {}
... |
LL | | Rc::new(String::from("foo"))
LL | | }
| |_^

error: cannot check whether the hidden type of opaque type satisfies auto traits
--> $DIR/auto-trait-leak.rs:21:10
|
LL | send(cycle1().clone());
| ---- ^^^^^^^^^^^^^^^^
| |
| required by a bound introduced by this call
|
note: opaque type is declared here
--> $DIR/auto-trait-leak.rs:11:16
|
LL | fn cycle1() -> impl Clone {
| ^^^^^^^^^^
note: this item depends on auto traits of the hidden type, but may also be registering the hidden type. This is not supported right now. You can try moving the opaque type and the item that actually registers a hidden type into a new submodule
--> $DIR/auto-trait-leak.rs:20:4
|
LL | fn cycle2() -> impl Clone {
| ^^^^^^
note: required by a bound in `send`
--> $DIR/auto-trait-leak.rs:4:12
|
LL | fn send<T: Send>(_: T) {}
| ^^^^ required by this bound in `send`

error: cannot check whether the hidden type of opaque type satisfies auto traits
--> $DIR/auto-trait-leak.rs:14:10
|
LL | send(cycle2().clone());
| ---- ^^^^^^^^^^^^^^^^
| |
| required by a bound introduced by this call
|
note: opaque type is declared here
--> $DIR/auto-trait-leak.rs:20:16
|
LL | fn cycle2() -> impl Clone {
| ^^^^^^^^^^
note: this item depends on auto traits of the hidden type, but may also be registering the hidden type. This is not supported right now. You can try moving the opaque type and the item that actually registers a hidden type into a new submodule
--> $DIR/auto-trait-leak.rs:11:4
|
LL | fn cycle1() -> impl Clone {
| ^^^^^^
note: required by a bound in `send`
--> $DIR/auto-trait-leak.rs:4:12
|
LL | fn send<T: Send>(_: T) {}
| ^^^^ required by this bound in `send`

error: aborting due to 4 previous errors

For more information about this error, try `rustc --explain E0391`.
2 changes: 2 additions & 0 deletions tests/ui/impl-trait/issue-103181-2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ where
B: Send, // <- a second bound
{
normalize(broken_fut(), ());
//~^ ERROR: cannot check whether the hidden type of opaque type satisfies auto traits
//~| ERROR: cannot check whether the hidden type of opaque type satisfies auto traits
}

fn main() {}
57 changes: 56 additions & 1 deletion tests/ui/impl-trait/issue-103181-2.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,61 @@ error[E0425]: cannot find value `ident_error` in this scope
LL | ident_error;
| ^^^^^^^^^^^ not found in this scope

error: aborting due to previous error
error: cannot check whether the hidden type of opaque type satisfies auto traits
--> $DIR/issue-103181-2.rs:26:15
|
LL | normalize(broken_fut(), ());
| --------- ^^^^^^^^^^^^
| |
| required by a bound introduced by this call
|
note: opaque type is declared here
--> $DIR/issue-103181-2.rs:11:23
|
LL | async fn broken_fut() {
| ^
note: this item depends on auto traits of the hidden type, but may also be registering the hidden type. This is not supported right now. You can try moving the opaque type and the item that actually registers a hidden type into a new submodule
--> $DIR/issue-103181-2.rs:20:10
|
LL | async fn iceice<A, B>()
| ^^^^^^
note: required for `impl Future<Output = ()>` to implement `SendFuture`
--> $DIR/issue-103181-2.rs:7:17
|
LL | impl<Fut: Send> SendFuture for Fut {
| ---- ^^^^^^^^^^ ^^^
| |
| unsatisfied trait bound introduced here
note: required by a bound in `normalize`
--> $DIR/issue-103181-2.rs:18:19
|
LL | fn normalize<Fut: SendFuture>(_: Fut, _: Fut::Output) {}
| ^^^^^^^^^^ required by this bound in `normalize`

error: cannot check whether the hidden type of opaque type satisfies auto traits
--> $DIR/issue-103181-2.rs:26:5
|
LL | normalize(broken_fut(), ());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: opaque type is declared here
--> $DIR/issue-103181-2.rs:11:23
|
LL | async fn broken_fut() {
| ^
note: this item depends on auto traits of the hidden type, but may also be registering the hidden type. This is not supported right now. You can try moving the opaque type and the item that actually registers a hidden type into a new submodule
--> $DIR/issue-103181-2.rs:20:10
|
LL | async fn iceice<A, B>()
| ^^^^^^
note: required for `impl Future<Output = ()>` to implement `SendFuture`
--> $DIR/issue-103181-2.rs:7:17
|
LL | impl<Fut: Send> SendFuture for Fut {
| ---- ^^^^^^^^^^ ^^^
| |
| unsatisfied trait bound introduced here

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0425`.
2 changes: 2 additions & 0 deletions tests/ui/type-alias-impl-trait/auto-trait-leakage3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
mod m {
pub type Foo = impl std::fmt::Debug;
//~^ ERROR: cycle detected when computing type of `m::Foo::{opaque#0}` [E0391]
//~| ERROR: cycle detected when computing type of `m::Foo::{opaque#0}` [E0391]

pub fn foo() -> Foo {
22_u32
}

pub fn bar() {
is_send(foo());
//~^ ERROR: cannot check whether the hidden type of `auto_trait_leakage3[211d]::m::Foo::{opaque#0}
}

fn is_send<T: Send>(_: T) {}
Expand Down
Loading

0 comments on commit 9e98feb

Please sign in to comment.