Skip to content

Commit 03b9e1d

Browse files
committed
Auto merge of #105409 - compiler-errors:closure-infer-cycle, r=jackh726
Don't deduce a signature that makes a closure cyclic Sometimes when elaborating supertrait bounds for closure signature inference, we end up deducing a closure signature that is cyclical because either a parameter or the return type references a projection mentioning `Self` that also has escaping bound vars, which means that it's not eagerly replaced with an inference variable. Interestingly, this is not *just* related to my PR that elaborates supertrait bounds for closure signature deduction. The committed test `supertrait-hint-cycle-3.rs` shows **stable** code that is fixed by this PR: ```rust trait Foo<'a> { type Input; } impl<F: Fn(u32)> Foo<'_> for F { type Input = u32; } fn needs_super<F: for<'a> Fn(<F as Foo<'a>>::Input) + for<'a> Foo<'a>>(_: F) {} fn main() { needs_super(|_: u32| {}); } ``` Fixes #105401 Fixes #105396 r? types
2 parents d26242d + fa2f31b commit 03b9e1d

File tree

7 files changed

+162
-10
lines changed

7 files changed

+162
-10
lines changed

compiler/rustc_hir_typeck/src/closure.rs

+31-7
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,15 @@ use rustc_infer::infer::{InferOk, InferResult};
1313
use rustc_macros::{TypeFoldable, TypeVisitable};
1414
use rustc_middle::ty::subst::InternalSubsts;
1515
use rustc_middle::ty::visit::TypeVisitable;
16-
use rustc_middle::ty::{self, Ty};
16+
use rustc_middle::ty::{self, Ty, TypeSuperVisitable, TypeVisitor};
1717
use rustc_span::source_map::Span;
1818
use rustc_target::spec::abi::Abi;
1919
use rustc_trait_selection::traits;
2020
use rustc_trait_selection::traits::error_reporting::ArgKind;
2121
use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
2222
use std::cmp;
2323
use std::iter;
24+
use std::ops::ControlFlow;
2425

2526
/// What signature do we *expect* the closure to have from context?
2627
#[derive(Debug, Clone, TypeFoldable, TypeVisitable)]
@@ -54,7 +55,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
5455
// closure sooner rather than later, so first examine the expected
5556
// type, and see if can glean a closure kind from there.
5657
let (expected_sig, expected_kind) = match expected.to_option(self) {
57-
Some(ty) => self.deduce_expectations_from_expected_type(ty),
58+
Some(ty) => self.deduce_closure_signature(ty),
5859
None => (None, None),
5960
};
6061
let body = self.tcx.hir().body(closure.body);
@@ -162,13 +163,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
162163
/// Given the expected type, figures out what it can about this closure we
163164
/// are about to type check:
164165
#[instrument(skip(self), level = "debug")]
165-
fn deduce_expectations_from_expected_type(
166+
fn deduce_closure_signature(
166167
&self,
167168
expected_ty: Ty<'tcx>,
168169
) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
169170
match *expected_ty.kind() {
170171
ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => self
171-
.deduce_signature_from_predicates(
172+
.deduce_closure_signature_from_predicates(
173+
expected_ty,
172174
self.tcx.bound_explicit_item_bounds(def_id).subst_iter_copied(self.tcx, substs),
173175
),
174176
ty::Dynamic(ref object_type, ..) => {
@@ -181,7 +183,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
181183
.and_then(|did| self.tcx.fn_trait_kind_from_def_id(did));
182184
(sig, kind)
183185
}
184-
ty::Infer(ty::TyVar(vid)) => self.deduce_signature_from_predicates(
186+
ty::Infer(ty::TyVar(vid)) => self.deduce_closure_signature_from_predicates(
187+
self.tcx.mk_ty_var(self.root_var(vid)),
185188
self.obligations_for_self_ty(vid).map(|obl| (obl.predicate, obl.cause.span)),
186189
),
187190
ty::FnPtr(sig) => {
@@ -192,8 +195,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
192195
}
193196
}
194197

195-
fn deduce_signature_from_predicates(
198+
fn deduce_closure_signature_from_predicates(
196199
&self,
200+
expected_ty: Ty<'tcx>,
197201
predicates: impl DoubleEndedIterator<Item = (ty::Predicate<'tcx>, Span)>,
198202
) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
199203
let mut expected_sig = None;
@@ -214,13 +218,33 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
214218
if expected_sig.is_none()
215219
&& let ty::PredicateKind::Clause(ty::Clause::Projection(proj_predicate)) = bound_predicate.skip_binder()
216220
{
217-
expected_sig = self.normalize(
221+
let inferred_sig = self.normalize(
218222
obligation.cause.span,
219223
self.deduce_sig_from_projection(
220224
Some(obligation.cause.span),
221225
bound_predicate.rebind(proj_predicate),
222226
),
223227
);
228+
// Make sure that we didn't infer a signature that mentions itself.
229+
// This can happen when we elaborate certain supertrait bounds that
230+
// mention projections containing the `Self` type. See #105401.
231+
struct MentionsTy<'tcx> {
232+
expected_ty: Ty<'tcx>,
233+
}
234+
impl<'tcx> TypeVisitor<'tcx> for MentionsTy<'tcx> {
235+
type BreakTy = ();
236+
237+
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
238+
if t == self.expected_ty {
239+
ControlFlow::BREAK
240+
} else {
241+
t.super_visit_with(self)
242+
}
243+
}
244+
}
245+
if inferred_sig.visit_with(&mut MentionsTy { expected_ty }).is_continue() {
246+
expected_sig = inferred_sig;
247+
}
224248
}
225249

226250
// Even if we can't infer the full signature, we may be able to

compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ use rustc_infer::infer::error_reporting::TypeErrCtxt;
3333
use rustc_infer::infer::{InferOk, TypeTrace};
3434
use rustc_middle::traits::select::OverflowError;
3535
use rustc_middle::ty::abstract_const::NotConstEvaluatable;
36-
use rustc_middle::ty::error::ExpectedFound;
36+
use rustc_middle::ty::error::{ExpectedFound, TypeError};
3737
use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable};
3838
use rustc_middle::ty::print::{with_forced_trimmed_paths, FmtPrinter, Print};
3939
use rustc_middle::ty::{
@@ -1215,6 +1215,25 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
12151215
}
12161216
}
12171217

1218+
OutputTypeParameterMismatch(
1219+
found_trait_ref,
1220+
expected_trait_ref,
1221+
terr @ TypeError::CyclicTy(_),
1222+
) => {
1223+
let self_ty = found_trait_ref.self_ty().skip_binder();
1224+
let (cause, terr) = if let ty::Closure(def_id, _) = self_ty.kind() {
1225+
(
1226+
ObligationCause::dummy_with_span(tcx.def_span(def_id)),
1227+
TypeError::CyclicTy(self_ty),
1228+
)
1229+
} else {
1230+
(obligation.cause.clone(), terr)
1231+
};
1232+
self.report_and_explain_type_error(
1233+
TypeTrace::poly_trait_refs(&cause, true, expected_trait_ref, found_trait_ref),
1234+
terr,
1235+
)
1236+
}
12181237
OutputTypeParameterMismatch(found_trait_ref, expected_trait_ref, _) => {
12191238
let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
12201239
let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// check-pass
2+
3+
trait Foo<'a> {
4+
type Input;
5+
}
6+
7+
impl<F: Fn(u32)> Foo<'_> for F {
8+
type Input = u32;
9+
}
10+
11+
trait SuperFn: for<'a> Foo<'a> + for<'a> Fn(<Self as Foo<'a>>::Input) {}
12+
impl<T> SuperFn for T where T: for<'a> Fn(<Self as Foo<'a>>::Input) + for<'a> Foo<'a> {}
13+
14+
fn needs_super(_: impl SuperFn) {}
15+
16+
fn main() {
17+
needs_super(|_: u32| {});
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// check-pass
2+
3+
4+
trait Foo<'a> {
5+
type Input;
6+
}
7+
8+
impl<F: Fn(u32)> Foo<'_> for F {
9+
type Input = u32;
10+
}
11+
12+
fn needs_super<F: for<'a> Fn(<F as Foo<'a>>::Input) + for<'a> Foo<'a>>(_: F) {}
13+
14+
fn main() {
15+
needs_super(|_: u32| {});
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// edition:2021
2+
// check-pass
3+
4+
#![feature(type_alias_impl_trait)]
5+
#![feature(closure_lifetime_binder)]
6+
7+
use std::future::Future;
8+
9+
trait AsyncFn<I, R>: FnMut(I) -> Self::Fut {
10+
type Fut: Future<Output = R>;
11+
}
12+
13+
impl<F, I, R, Fut> AsyncFn<I, R> for F
14+
where
15+
Fut: Future<Output = R>,
16+
F: FnMut(I) -> Fut,
17+
{
18+
type Fut = Fut;
19+
}
20+
21+
async fn call<C, R, F>(mut ctx: C, mut f: F) -> Result<R, ()>
22+
where
23+
F: for<'a> AsyncFn<&'a mut C, Result<R, ()>>,
24+
{
25+
loop {
26+
match f(&mut ctx).await {
27+
Ok(val) => return Ok(val),
28+
Err(_) => continue,
29+
}
30+
}
31+
}
32+
33+
trait Cap<'a> {}
34+
impl<T> Cap<'_> for T {}
35+
36+
fn works(ctx: &mut usize) {
37+
let mut inner = 0;
38+
39+
type Ret<'a, 'b: 'a> = impl Future<Output = Result<usize, ()>> + 'a + Cap<'b>;
40+
41+
let callback = for<'a, 'b> |c: &'a mut &'b mut usize| -> Ret<'a, 'b> {
42+
inner += 1;
43+
async move {
44+
let _c = c;
45+
Ok(1usize)
46+
}
47+
};
48+
call(ctx, callback);
49+
}
50+
51+
fn doesnt_work_but_should(ctx: &mut usize) {
52+
let mut inner = 0;
53+
54+
type Ret<'a, 'b: 'a> = impl Future<Output = Result<usize, ()>> + 'a + Cap<'b>;
55+
56+
call(ctx, for<'a, 'b> |c: &'a mut &'b mut usize| -> Ret<'a, 'b> {
57+
inner += 1;
58+
async move {
59+
let _c = c;
60+
Ok(1usize)
61+
}
62+
});
63+
}
64+
65+
fn main() {}

src/test/ui/issues/issue-25439.stderr

+6-1
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,17 @@ error[E0644]: closure/generator type that references itself
22
--> $DIR/issue-25439.rs:8:9
33
|
44
LL | fix(|_, x| x);
5-
| ^^^^^^^^ cyclic type of infinite size
5+
| ^^^^^^ cyclic type of infinite size
66
|
77
= note: closures cannot capture themselves or take themselves as argument;
88
this error may be the result of a recent compiler bug-fix,
99
see issue #46062 <https://github.com/rust-lang/rust/issues/46062>
1010
for more information
11+
note: required by a bound in `fix`
12+
--> $DIR/issue-25439.rs:3:33
13+
|
14+
LL | fn fix<F>(f: F) -> i32 where F: Fn(Helper<F>, i32) -> i32 {
15+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fix`
1116

1217
error: aborting due to previous error
1318

src/test/ui/unboxed-closures/unboxed-closure-no-cyclic-sig.stderr

+6-1
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,17 @@ error[E0644]: closure/generator type that references itself
22
--> $DIR/unboxed-closure-no-cyclic-sig.rs:8:7
33
|
44
LL | g(|_| { });
5-
| ^^^^^^^^ cyclic type of infinite size
5+
| ^^^ cyclic type of infinite size
66
|
77
= note: closures cannot capture themselves or take themselves as argument;
88
this error may be the result of a recent compiler bug-fix,
99
see issue #46062 <https://github.com/rust-lang/rust/issues/46062>
1010
for more information
11+
note: required by a bound in `g`
12+
--> $DIR/unboxed-closure-no-cyclic-sig.rs:5:24
13+
|
14+
LL | fn g<F>(_: F) where F: FnOnce(Option<F>) {}
15+
| ^^^^^^^^^^^^^^^^^ required by this bound in `g`
1116

1217
error: aborting due to previous error
1318

0 commit comments

Comments
 (0)