]> git.lizzy.rs Git - rust.git/commitdiff
Properly use parent generics for opaque types
authorAaron Hill <aa1ronham@gmail.com>
Sun, 9 Feb 2020 23:38:21 +0000 (18:38 -0500)
committerAaron Hill <aa1ronham@gmail.com>
Sun, 9 Feb 2020 23:45:12 +0000 (18:45 -0500)
Fixes #67844

Previously, opaque types would only get parent generics if they
a return-position-impl-trait (e.g. `fn foo<A>() -> impl MyTrait<A>`).

However, it's possible for opaque types to be nested inside one another:

```rust
trait WithAssoc { type AssocType; }

trait WithParam<A> {}

type Return<A> = impl WithAssoc<AssocType = impl WithParam<A>>;
```

When this occurs, we need to ensure that the nested opaque types
properly inherit generic parameters from their parent opaque type.

This commit fixes the `generics_of` query to take the parent item
into account when determining the generics for an opaque type.

src/librustc_typeck/collect.rs
src/test/ui/type-alias-impl-trait/issue-67844-nested-opaque.rs [new file with mode: 0644]

index 2a450f4b4e8b1852e7f1c9d1f9f68a35a5d38ae8..49b1bfb72a3553e64cfb00ac319fe3fc7be6c8d2 100644 (file)
@@ -1054,7 +1054,19 @@ fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
             Some(tcx.closure_base_def_id(def_id))
         }
         Node::Item(item) => match item.kind {
-            ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => impl_trait_fn,
+            ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
+                impl_trait_fn.or_else(|| {
+                    let parent_id = tcx.hir().get_parent_item(hir_id);
+                    // This opaque type might occur inside another opaque type
+                    // (e.g. `impl Foo<MyType = impl Bar<A>>`)
+                    if parent_id != hir_id && parent_id != CRATE_HIR_ID {
+                        debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);
+                        Some(tcx.hir().local_def_id(parent_id))
+                    } else {
+                        None
+                    }
+                })
+            }
             _ => None,
         },
         _ => None,
diff --git a/src/test/ui/type-alias-impl-trait/issue-67844-nested-opaque.rs b/src/test/ui/type-alias-impl-trait/issue-67844-nested-opaque.rs
new file mode 100644 (file)
index 0000000..2f844b4
--- /dev/null
@@ -0,0 +1,32 @@
+// check-pass
+// Regression test for issue #67844
+// Ensures that we properly handle nested TAIT occurences
+// with generic parameters
+
+#![feature(type_alias_impl_trait)]
+
+trait WithAssoc { type AssocType; }
+
+trait WithParam<A> {}
+
+type Return<A> = impl WithAssoc<AssocType = impl WithParam<A>>;
+
+struct MyParam;
+impl<A> WithParam<A> for MyParam {}
+
+struct MyStruct;
+
+impl WithAssoc for MyStruct {
+    type AssocType = MyParam;
+}
+
+
+fn my_fun<A>() -> Return<A> {
+    MyStruct
+}
+
+fn my_other_fn<A>() -> impl WithAssoc<AssocType = impl WithParam<A>> {
+    MyStruct
+}
+
+fn main() {}