Skip to content

Commit 483a83b

Browse files
committed
Auto merge of #66178 - Aaron1011:fix/opaque-normalize, r=varkor
Fix opaque types resulting from projections in function signature When we normalize the types in a function signature, we may end up resolving a projection to an opaque type (e.g. `Self::MyType` when we have `type MyType = impl SomeTrait`). When the projection is resolved, we will instantiate the generic parameters into fresh inference variables. While we do want to normalize projections to opaque types, we don't want to replace the explicit generic parameters (e.g. `T` in `impl MyTrait<T>`) with inference variables. We want the opaque type in the function signature to be eligible to be a defining use of that opaque type - adding inference variables prevents this, since the opaque type substs now appears to refer to some specific type, rather than a generic type. To resolve this issue, we inspect the opaque types in the function signature after normalization. Any inference variables in the substs are replaced with the corresponding generic parameter in the identity substs (e.g. `T` in `impl MyTrait<T>`). Note that normalization is the only way that we can end up with inference variables in opaque substs in a function signature - users have no way of getting inference variables into a function signature. Note that all of this refers to the opaque type (ty::Opaque) and its subst - *not* to the underlying type. Fixes #59342
2 parents a44774c + df3f338 commit 483a83b

13 files changed

+226
-47
lines changed

src/librustc_typeck/check/mod.rs

+108-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ use rustc::ty::{
114114
use rustc::ty::adjustment::{
115115
Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast
116116
};
117-
use rustc::ty::fold::TypeFoldable;
117+
use rustc::ty::fold::{TypeFoldable, TypeFolder};
118118
use rustc::ty::query::Providers;
119119
use rustc::ty::subst::{
120120
GenericArgKind, Subst, InternalSubsts, SubstsRef, UserSelfTy, UserSubsts,
@@ -872,6 +872,111 @@ fn used_trait_imports(tcx: TyCtxt<'_>, def_id: DefId) -> &DefIdSet {
872872
&*tcx.typeck_tables_of(def_id).used_trait_imports
873873
}
874874

875+
/// Inspects the substs of opaque types, replacing any inference variables
876+
/// with proper generic parameter from the identity substs.
877+
///
878+
/// This is run after we normalize the function signature, to fix any inference
879+
/// variables introduced by the projection of associated types. This ensures that
880+
/// any opaque types used in the signature continue to refer to generic parameters,
881+
/// allowing them to be considered for defining uses in the function body
882+
///
883+
/// For example, consider this code.
884+
///
885+
/// ```rust
886+
/// trait MyTrait {
887+
/// type MyItem;
888+
/// fn use_it(self) -> Self::MyItem
889+
/// }
890+
/// impl<T, I> MyTrait for T where T: Iterator<Item = I> {
891+
/// type MyItem = impl Iterator<Item = I>;
892+
/// fn use_it(self) -> Self::MyItem {
893+
/// self
894+
/// }
895+
/// }
896+
/// ```
897+
///
898+
/// When we normalize the signature of `use_it` from the impl block,
899+
/// we will normalize `Self::MyItem` to the opaque type `impl Iterator<Item = I>`
900+
/// However, this projection result may contain inference variables, due
901+
/// to the way that projection works. We didn't have any inference variables
902+
/// in the signature to begin with - leaving them in will cause us to incorrectly
903+
/// conclude that we don't have a defining use of `MyItem`. By mapping inference
904+
/// variables back to the actual generic parameters, we will correctly see that
905+
/// we have a defining use of `MyItem`
906+
fn fixup_opaque_types<'tcx, T>(tcx: TyCtxt<'tcx>, val: &T) -> T where T: TypeFoldable<'tcx> {
907+
struct FixupFolder<'tcx> {
908+
tcx: TyCtxt<'tcx>
909+
}
910+
911+
impl<'tcx> TypeFolder<'tcx> for FixupFolder<'tcx> {
912+
fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
913+
self.tcx
914+
}
915+
916+
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
917+
match ty.kind {
918+
ty::Opaque(def_id, substs) => {
919+
debug!("fixup_opaque_types: found type {:?}", ty);
920+
// Here, we replace any inference variables that occur within
921+
// the substs of an opaque type. By definition, any type occuring
922+
// in the substs has a corresponding generic parameter, which is what
923+
// we replace it with.
924+
// This replacement is only run on the function signature, so any
925+
// inference variables that we come across must be the rust of projection
926+
// (there's no other way for a user to get inference variables into
927+
// a function signature).
928+
if ty.needs_infer() {
929+
let new_substs = InternalSubsts::for_item(self.tcx, def_id, |param, _| {
930+
let old_param = substs[param.index as usize];
931+
match old_param.unpack() {
932+
GenericArgKind::Type(old_ty) => {
933+
if let ty::Infer(_) = old_ty.kind {
934+
// Replace inference type with a generic parameter
935+
self.tcx.mk_param_from_def(param)
936+
} else {
937+
old_param.fold_with(self)
938+
}
939+
},
940+
GenericArgKind::Const(old_const) => {
941+
if let ty::ConstKind::Infer(_) = old_const.val {
942+
// This should never happen - we currently do not support
943+
// 'const projections', e.g.:
944+
// `impl<T: SomeTrait> MyTrait for T where <T as SomeTrait>::MyConst == 25`
945+
// which should be the only way for us to end up with a const inference
946+
// variable after projection. If Rust ever gains support for this kind
947+
// of projection, this should *probably* be changed to
948+
// `self.tcx.mk_param_from_def(param)`
949+
bug!("Found infer const: `{:?}` in opaque type: {:?}",
950+
old_const, ty);
951+
} else {
952+
old_param.fold_with(self)
953+
}
954+
}
955+
GenericArgKind::Lifetime(old_region) => {
956+
if let RegionKind::ReVar(_) = old_region {
957+
self.tcx.mk_param_from_def(param)
958+
} else {
959+
old_param.fold_with(self)
960+
}
961+
}
962+
}
963+
});
964+
let new_ty = self.tcx.mk_opaque(def_id, new_substs);
965+
debug!("fixup_opaque_types: new type: {:?}", new_ty);
966+
new_ty
967+
} else {
968+
ty
969+
}
970+
},
971+
_ => ty.super_fold_with(self)
972+
}
973+
}
974+
}
975+
976+
debug!("fixup_opaque_types({:?})", val);
977+
val.fold_with(&mut FixupFolder { tcx })
978+
}
979+
875980
fn typeck_tables_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TypeckTables<'_> {
876981
// Closures' tables come from their outermost function,
877982
// as they are part of the same "inference environment".
@@ -911,6 +1016,8 @@ fn typeck_tables_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TypeckTables<'_> {
9111016
param_env,
9121017
&fn_sig);
9131018

1019+
let fn_sig = fixup_opaque_types(tcx, &fn_sig);
1020+
9141021
let fcx = check_fn(&inh, param_env, fn_sig, decl, id, body, None).0;
9151022
fcx
9161023
} else {

src/librustc_typeck/collect.rs

+15-5
Original file line numberDiff line numberDiff line change
@@ -1617,11 +1617,18 @@ fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
16171617
ty::Param(_) => true,
16181618
_ => false,
16191619
};
1620-
if !substs.types().all(is_param) {
1621-
self.tcx.sess.span_err(
1622-
span,
1623-
"defining opaque type use does not fully define opaque type",
1624-
);
1620+
let bad_substs: Vec<_> = substs.types().enumerate()
1621+
.filter(|(_, ty)| !is_param(ty)).collect();
1622+
if !bad_substs.is_empty() {
1623+
let identity_substs = InternalSubsts::identity_for_item(self.tcx, self.def_id);
1624+
for (i, bad_subst) in bad_substs {
1625+
self.tcx.sess.span_err(
1626+
span,
1627+
&format!("defining opaque type use does not fully define opaque type: \
1628+
generic parameter `{}` is specified as concrete type `{}`",
1629+
identity_substs.type_at(i), bad_subst)
1630+
);
1631+
}
16251632
} else if let Some((prev_span, prev_ty, ref prev_indices)) = self.found {
16261633
let mut ty = concrete_type.walk().fuse();
16271634
let mut p_ty = prev_ty.walk().fuse();
@@ -2059,6 +2066,9 @@ fn explicit_predicates_of(
20592066
ty::print::with_no_queries(|| {
20602067
let substs = InternalSubsts::identity_for_item(tcx, def_id);
20612068
let opaque_ty = tcx.mk_opaque(def_id, substs);
2069+
debug!("explicit_predicates_of({:?}): created opaque type {:?}",
2070+
def_id, opaque_ty);
2071+
20622072

20632073
// Collect the bounds, i.e., the `A + B + 'c` in `impl A + B + 'c`.
20642074
let bounds = AstConv::compute_bounds(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Regression test for issue #59342
2+
// Checks that we properly detect defining uses of opaque
3+
// types in 'item' position when generic parameters are involved
4+
//
5+
// run-pass
6+
#![feature(type_alias_impl_trait)]
7+
8+
trait Meow {
9+
type MeowType;
10+
fn meow(self) -> Self::MeowType;
11+
}
12+
13+
impl<T, I> Meow for I
14+
where I: Iterator<Item = T>
15+
{
16+
type MeowType = impl Iterator<Item = T>;
17+
fn meow(self) -> Self::MeowType {
18+
self
19+
}
20+
}
21+
22+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Tests that we properly detect defining usages when using
2+
// const generics in an associated opaque type
3+
// check-pass
4+
5+
#![feature(type_alias_impl_trait)]
6+
#![feature(const_generics)]
7+
//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash
8+
9+
trait UnwrapItemsExt<const C: usize> {
10+
type Iter;
11+
fn unwrap_items(self) -> Self::Iter;
12+
}
13+
14+
struct MyStruct<const C: usize> {}
15+
16+
trait MyTrait<'a, const C: usize> {
17+
type MyItem;
18+
const MY_CONST: usize;
19+
}
20+
21+
impl<'a, const C: usize> MyTrait<'a, {C}> for MyStruct<{C}> {
22+
type MyItem = u8;
23+
const MY_CONST: usize = C;
24+
}
25+
26+
impl<'a, I, const C: usize> UnwrapItemsExt<{C}> for I
27+
where
28+
{
29+
type Iter = impl MyTrait<'a, {C}>;
30+
31+
fn unwrap_items(self) -> Self::Iter {
32+
MyStruct::<{C}> {}
33+
}
34+
}
35+
36+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
warning: the feature `const_generics` is incomplete and may cause the compiler to crash
2+
--> $DIR/assoc-type-const.rs:6:12
3+
|
4+
LL | #![feature(const_generics)]
5+
| ^^^^^^^^^^^^^^
6+
|
7+
= note: `#[warn(incomplete_features)]` on by default
8+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Tests that we still detect defining usages when
2+
// lifetimes are used in an associated opaque type
3+
// check-pass
4+
5+
#![feature(type_alias_impl_trait)]
6+
7+
trait UnwrapItemsExt {
8+
type Iter;
9+
fn unwrap_items(self) -> Self::Iter;
10+
}
11+
12+
struct MyStruct {}
13+
14+
trait MyTrait<'a> {}
15+
16+
impl<'a> MyTrait<'a> for MyStruct {}
17+
18+
impl<'a, I> UnwrapItemsExt for I
19+
where
20+
{
21+
type Iter = impl MyTrait<'a>;
22+
23+
fn unwrap_items(self) -> Self::Iter {
24+
MyStruct {}
25+
}
26+
}
27+
28+
fn main() {}

src/test/ui/type-alias-impl-trait/bound_reduction2.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
error: defining opaque type use does not fully define opaque type
1+
error: defining opaque type use does not fully define opaque type: generic parameter `V` is specified as concrete type `<T as TraitWithAssoc>::Assoc`
22
--> $DIR/bound_reduction2.rs:17:1
33
|
44
LL | / fn foo_desugared<T: TraitWithAssoc>(_: T) -> Foo<T::Assoc> {

src/test/ui/type-alias-impl-trait/generic_nondefining_use.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ error: at least one trait must be specified
44
LL | type Cmp<T> = impl 'static;
55
| ^^^^^^^^^^^^
66

7-
error: defining opaque type use does not fully define opaque type
7+
error: defining opaque type use does not fully define opaque type: generic parameter `T` is specified as concrete type `u32`
88
--> $DIR/generic_nondefining_use.rs:11:1
99
|
1010
LL | / fn cmp() -> Cmp<u32> {

src/test/ui/type-alias-impl-trait/issue-58887.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// run-pass
2+
13
#![feature(type_alias_impl_trait)]
24

35
trait UnwrapItemsExt {
@@ -11,11 +13,8 @@ where
1113
E: std::fmt::Debug,
1214
{
1315
type Iter = impl Iterator<Item = T>;
14-
//~^ ERROR: could not find defining uses
1516

1617
fn unwrap_items(self) -> Self::Iter {
17-
//~^ ERROR: type parameter `T` is part of concrete type
18-
//~| ERROR: type parameter `E` is part of concrete type
1918
self.map(|x| x.unwrap())
2019
}
2120
}

src/test/ui/type-alias-impl-trait/issue-58887.stderr

-30
This file was deleted.

src/test/ui/type-alias-impl-trait/issue-60564.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ where
1818
{
1919
type BitsIter = IterBitsIter<T, E, u8>;
2020
fn iter_bits(self, n: u8) -> Self::BitsIter {
21-
//~^ ERROR type parameter `E` is part of concrete type but not used
21+
//~^ ERROR defining opaque type use does not fully define opaque type
2222
(0u8..n)
2323
.rev()
2424
.map(move |shift| ((self >> T::from(shift)) & T::from(1)).try_into().unwrap())

src/test/ui/type-alias-impl-trait/issue-60564.stderr

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
error: type parameter `E` is part of concrete type but not used in parameter list for the `impl Trait` type alias
2-
--> $DIR/issue-60564.rs:20:49
1+
error: defining opaque type use does not fully define opaque type: generic parameter `I` is specified as concrete type `u8`
2+
--> $DIR/issue-60564.rs:20:5
33
|
4-
LL | fn iter_bits(self, n: u8) -> Self::BitsIter {
5-
| _________________________________________________^
4+
LL | / fn iter_bits(self, n: u8) -> Self::BitsIter {
65
LL | |
76
LL | | (0u8..n)
87
LL | | .rev()

src/test/ui/type-alias-impl-trait/not_a_defining_use.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
error: defining opaque type use does not fully define opaque type
1+
error: defining opaque type use does not fully define opaque type: generic parameter `U` is specified as concrete type `u32`
22
--> $DIR/not_a_defining_use.rs:9:1
33
|
44
LL | / fn two<T: Debug>(t: T) -> Two<T, u32> {

0 commit comments

Comments
 (0)