Skip to content

Commit a9af75c

Browse files
committed
Give opaque types a better coherence error
1 parent 1d12c3c commit a9af75c

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

compiler/rustc_hir_analysis/src/coherence/orphan.rs

+15-8
Original file line numberDiff line numberDiff line change
@@ -184,11 +184,19 @@ fn emit_orphan_check_error<'tcx>(
184184
ty::Adt(def, _) => tcx.mk_adt(*def, ty::List::empty()),
185185
_ => ty,
186186
};
187-
let this = "this".to_string();
188-
let (ty, postfix) = match &ty.kind() {
189-
ty::Slice(_) => (this, " because slices are always foreign"),
190-
ty::Array(..) => (this, " because arrays are always foreign"),
191-
ty::Tuple(..) => (this, " because tuples are always foreign"),
187+
let msg = |ty: &str, postfix: &str| {
188+
format!("{ty} is not defined in the current crate{postfix}")
189+
};
190+
let this = |name: &str| msg("this", &format!(" because {name} are always foreign"));
191+
let msg = match &ty.kind() {
192+
ty::Slice(_) => this("slices"),
193+
ty::Array(..) => this("arrays"),
194+
ty::Tuple(..) => this("tuples"),
195+
ty::Alias(ty::Opaque, ..) => {
196+
"type alias impl trait is treated as if it were foreign, \
197+
because its hidden type could be from a foreign crate"
198+
.to_string()
199+
}
192200
ty::RawPtr(ptr_ty) => {
193201
emit_newtype_suggestion_for_raw_ptr(
194202
full_impl_span,
@@ -198,12 +206,11 @@ fn emit_orphan_check_error<'tcx>(
198206
&mut err,
199207
);
200208

201-
(format!("`{}`", ty), " because raw pointers are always foreign")
209+
msg(&format!("`{ty}`"), " because raw pointers are always foreign")
202210
}
203-
_ => (format!("`{}`", ty), ""),
211+
_ => msg(&format!("`{ty}`"), ""),
204212
};
205213

206-
let msg = format!("{} is not defined in the current crate{}", ty, postfix);
207214
if is_target_ty {
208215
// Point at `D<A>` in `impl<A, B> for C<B> in D<A>`
209216
err.span_label(self_ty_span, &msg);

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ error[E0117]: only traits defined in the current crate can be implemented for ar
44
LL | impl<T> foreign_crate::ForeignTrait for AliasOfForeignType<T> {}
55
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------------
66
| | |
7-
| | `AliasOfForeignType<T>` is not defined in the current crate
7+
| | type alias impl trait is treated as if it were foreign, because its hidden type could be from a foreign crate
88
| impl doesn't use only types from inside the current crate
99
|
1010
= note: define and implement a trait or new type instead

0 commit comments

Comments
 (0)