1use std::fmt::Debug;
2use std::ops::ControlFlow;
34use derive_where::derive_where;
5use rustc_type_ir::inherent::*;
6use rustc_type_ir::{
7selfas ty, InferCtxtLike, Interner, TrivialTypeTraversalImpls, TypeVisitable,
8TypeVisitableExt, TypeVisitor,
9};
10use tracing::instrument;
1112/// Whether we do the orphan check relative to this crate or to some remote crate.
13#[derive(#[automatically_derived]
impl ::core::marker::Copy for InCrate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InCrate {
#[inline]
fn clone(&self) -> InCrate {
let _: ::core::clone::AssertParamIsClone<OrphanCheckMode>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for InCrate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
InCrate::Local { mode: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Local",
"mode", &__self_0),
InCrate::Remote => ::core::fmt::Formatter::write_str(f, "Remote"),
}
}
}Debug)]
14pub enum InCrate {
15 Local { mode: OrphanCheckMode },
16 Remote,
17}
1819#[derive(#[automatically_derived]
impl ::core::marker::Copy for OrphanCheckMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for OrphanCheckMode {
#[inline]
fn clone(&self) -> OrphanCheckMode { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for OrphanCheckMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
OrphanCheckMode::Proper => "Proper",
OrphanCheckMode::Compat => "Compat",
})
}
}Debug)]
20pub enum OrphanCheckMode {
21/// Proper orphan check.
22Proper,
23/// Improper orphan check for backward compatibility.
24 ///
25 /// In this mode, type params inside projections are considered to be covered
26 /// even if the projection may normalize to a type that doesn't actually cover
27 /// them. This is unsound. See also [#124559] and [#99554].
28 ///
29 /// [#124559]: https://github.com/rust-lang/rust/issues/124559
30 /// [#99554]: https://github.com/rust-lang/rust/issues/99554
31Compat,
32}
3334#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Conflict {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Conflict::Upstream => "Upstream",
Conflict::Downstream => "Downstream",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for Conflict { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Conflict {
#[inline]
fn clone(&self) -> Conflict { *self }
}Clone)]
35pub enum Conflict {
36 Upstream,
37 Downstream,
38}
3940/// Returns whether all impls which would apply to the `trait_ref`
41/// e.g. `Ty: Trait<Arg>` are already known in the local crate.
42///
43/// This both checks whether any downstream or sibling crates could
44/// implement it and whether an upstream crate can add this impl
45/// without breaking backwards compatibility.
46x;#[instrument(level = "debug", skip(infcx, lazily_normalize_ty), ret)]47pub fn trait_ref_is_knowable<Infcx, I, E>(
48 infcx: &Infcx,
49 trait_ref: ty::TraitRef<I>,
50mut lazily_normalize_ty: impl FnMut(I::Ty) -> Result<I::Ty, E>,
51) -> Result<Result<(), Conflict>, E>
52where
53Infcx: InferCtxtLike<Interner = I>,
54 I: Interner,
55 E: Debug,
56{
57if orphan_check_trait_ref(infcx, trait_ref, InCrate::Remote, &mut lazily_normalize_ty)?.is_ok()
58 {
59// A downstream or cousin crate is allowed to implement some
60 // generic parameters of this trait-ref.
61return Ok(Err(Conflict::Downstream));
62 }
6364if trait_ref_is_local_or_fundamental(infcx.cx(), trait_ref) {
65// This is a local or fundamental trait, so future-compatibility
66 // is no concern. We know that downstream/cousin crates are not
67 // allowed to implement a generic parameter of this trait ref,
68 // which means impls could only come from dependencies of this
69 // crate, which we already know about.
70return Ok(Ok(()));
71 }
7273// This is a remote non-fundamental trait, so if another crate
74 // can be the "final owner" of the generic parameters of this trait-ref,
75 // they are allowed to implement it future-compatibly.
76 //
77 // However, if we are a final owner, then nobody else can be,
78 // and if we are an intermediate owner, then we don't care
79 // about future-compatibility, which means that we're OK if
80 // we are an owner.
81if orphan_check_trait_ref(
82 infcx,
83 trait_ref,
84 InCrate::Local { mode: OrphanCheckMode::Proper },
85&mut lazily_normalize_ty,
86 )?
87.is_ok()
88 {
89Ok(Ok(()))
90 } else {
91Ok(Err(Conflict::Upstream))
92 }
93}
9495pub fn trait_ref_is_local_or_fundamental<I: Interner>(tcx: I, trait_ref: ty::TraitRef<I>) -> bool {
96trait_ref.def_id.is_local() || tcx.trait_is_fundamental(trait_ref.def_id)
97}
9899impl<I: ::rustc_type_ir::Interner> ::rustc_type_ir::TypeFoldable<I> for
IsFirstInputType {
fn try_fold_with<F: ::rustc_type_ir::FallibleTypeFolder<I>>(self,
_: &mut F) -> ::std::result::Result<Self, F::Error> {
Ok(self)
}
#[inline]
fn fold_with<F: ::rustc_type_ir::TypeFolder<I>>(self, _: &mut F) -> Self {
self
}
}
impl<I: ::rustc_type_ir::Interner> ::rustc_type_ir::TypeVisitable<I> for
IsFirstInputType {
#[inline]
fn visit_with<F: ::rustc_type_ir::TypeVisitor<I>>(&self, _: &mut F)
-> F::Result {
<F::Result as ::rustc_type_ir::VisitorResult>::output()
}
}TrivialTypeTraversalImpls! { IsFirstInputType, }100101#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsFirstInputType {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
IsFirstInputType::No => "No",
IsFirstInputType::Yes => "Yes",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for IsFirstInputType { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsFirstInputType {
#[inline]
fn clone(&self) -> IsFirstInputType { *self }
}Clone)]
102pub enum IsFirstInputType {
103 No,
104 Yes,
105}
106107impl From<bool> for IsFirstInputType {
108fn from(b: bool) -> IsFirstInputType {
109match b {
110false => IsFirstInputType::No,
111true => IsFirstInputType::Yes,
112 }
113 }
114}
115116#[automatically_derived]
impl<I: Interner, T> ::core::fmt::Debug for OrphanCheckErr<I, T> where
I: Interner, T: Debug {
fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
-> ::core::fmt::Result {
match self {
OrphanCheckErr::NonLocalInputType(ref __field_0) => {
let mut __builder =
::core::fmt::Formatter::debug_tuple(__f,
"NonLocalInputType");
::core::fmt::DebugTuple::field(&mut __builder, __field_0);
::core::fmt::DebugTuple::finish(&mut __builder)
}
OrphanCheckErr::UncoveredTyParams(ref __field_0) => {
let mut __builder =
::core::fmt::Formatter::debug_tuple(__f,
"UncoveredTyParams");
::core::fmt::DebugTuple::field(&mut __builder, __field_0);
::core::fmt::DebugTuple::finish(&mut __builder)
}
}
}
}#[derive_where(Debug; I: Interner, T: Debug)]117pub enum OrphanCheckErr<I: Interner, T> {
118 NonLocalInputType(Vec<(I::Ty, IsFirstInputType)>),
119 UncoveredTyParams(UncoveredTyParams<I, T>),
120}
121122#[automatically_derived]
impl<I: Interner, T> ::core::fmt::Debug for UncoveredTyParams<I, T> where
I: Interner, T: Debug {
fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
-> ::core::fmt::Result {
match self {
UncoveredTyParams {
uncovered: ref __field_uncovered,
local_ty: ref __field_local_ty } => {
let mut __builder =
::core::fmt::Formatter::debug_struct(__f,
"UncoveredTyParams");
::core::fmt::DebugStruct::field(&mut __builder, "uncovered",
__field_uncovered);
::core::fmt::DebugStruct::field(&mut __builder, "local_ty",
__field_local_ty);
::core::fmt::DebugStruct::finish(&mut __builder)
}
}
}
}#[derive_where(Debug; I: Interner, T: Debug)]123pub struct UncoveredTyParams<I: Interner, T> {
124pub uncovered: T,
125pub local_ty: Option<I::Ty>,
126}
127128/// Checks whether a trait-ref is potentially implementable by a crate.
129///
130/// The current rule is that a trait-ref orphan checks in a crate C:
131///
132/// 1. Order the parameters in the trait-ref in generic parameters order
133/// - Self first, others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
134/// 2. Of these type parameters, there is at least one type parameter
135/// in which, walking the type as a tree, you can reach a type local
136/// to C where all types in-between are fundamental types. Call the
137/// first such parameter the "local key parameter".
138/// - e.g., `Box<LocalType>` is OK, because you can visit LocalType
139/// going through `Box`, which is fundamental.
140/// - similarly, `FundamentalPair<Vec<()>, Box<LocalType>>` is OK for
141/// the same reason.
142/// - but (knowing that `Vec<T>` is non-fundamental, and assuming it's
143/// not local), `Vec<LocalType>` is bad, because `Vec<->` is between
144/// the local type and the type parameter.
145/// 3. Before this local type, no generic type parameter of the impl must
146/// be reachable through fundamental types.
147/// - e.g. `impl<T> Trait<LocalType> for Vec<T>` is fine, as `Vec` is not fundamental.
148/// - while `impl<T> Trait<LocalType> for Box<T>` results in an error, as `T` is
149/// reachable through the fundamental type `Box`.
150/// 4. Every type in the local key parameter not known in C, going
151/// through the parameter's type tree, must appear only as a subtree of
152/// a type local to C, with only fundamental types between the type
153/// local to C and the local key parameter.
154/// - e.g., `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
155/// is bad, because the only local type with `T` as a subtree is
156/// `LocalType<T>`, and `Vec<->` is between it and the type parameter.
157/// - similarly, `FundamentalPair<LocalType<T>, T>` is bad, because
158/// the second occurrence of `T` is not a subtree of *any* local type.
159/// - however, `LocalType<Vec<T>>` is OK, because `T` is a subtree of
160/// `LocalType<Vec<T>>`, which is local and has no types between it and
161/// the type parameter.
162///
163/// The orphan rules actually serve several different purposes:
164///
165/// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where
166/// every type local to one crate is unknown in the other) can't implement
167/// the same trait-ref. This follows because it can be seen that no such
168/// type can orphan-check in 2 such crates.
169///
170/// To check that a local impl follows the orphan rules, we check it in
171/// InCrate::Local mode, using type parameters for the "generic" types.
172///
173/// In InCrate::Local mode the orphan check succeeds if the current crate
174/// is definitely allowed to implement the given trait (no false positives).
175///
176/// 2. They ground negative reasoning for coherence. If a user wants to
177/// write both a conditional blanket impl and a specific impl, we need to
178/// make sure they do not overlap. For example, if we write
179/// ```ignore (illustrative)
180/// impl<T> IntoIterator for Vec<T>
181/// impl<T: Iterator> IntoIterator for T
182/// ```
183/// We need to be able to prove that `Vec<$0>: !Iterator` for every type $0.
184/// We can observe that this holds in the current crate, but we need to make
185/// sure this will also hold in all unknown crates (both "independent" crates,
186/// which we need for link-safety, and also child crates, because we don't want
187/// child crates to get error for impl conflicts in a *dependency*).
188///
189/// For that, we only allow negative reasoning if, for every assignment to the
190/// inference variables, every unknown crate would get an orphan error if they
191/// try to implement this trait-ref. To check for this, we use InCrate::Remote
192/// mode. That is sound because we already know all the impls from known crates.
193///
194/// In InCrate::Remote mode the orphan check succeeds if a foreign crate
195/// *could* implement the given trait (no false negatives).
196///
197/// 3. For non-`#[fundamental]` traits, they guarantee that parent crates can
198/// add "non-blanket" impls without breaking negative reasoning in dependent
199/// crates. This is the "rebalancing coherence" (RFC 1023) restriction.
200///
201/// For that, we only allow a crate to perform negative reasoning on
202/// non-local-non-`#[fundamental]` if there's a local key parameter as per (2).
203///
204/// Because we never perform negative reasoning generically (coherence does
205/// not involve type parameters), this can be interpreted as doing the full
206/// orphan check (using InCrate::Local mode), instantiating non-local known
207/// types for all inference variables.
208///
209/// This allows for crates to future-compatibly add impls as long as they
210/// can't apply to types with a key parameter in a child crate - applying
211/// the rules, this basically means that every type parameter in the impl
212/// must appear behind a non-fundamental type (because this is not a
213/// type-system requirement, crate owners might also go for "semantic
214/// future-compatibility" involving things such as sealed traits, but
215/// the above requirement is sufficient, and is necessary in "open world"
216/// cases).
217///
218/// Note that this function is never called for types that have both type
219/// parameters and inference variables.
220x;#[instrument(level = "trace", skip(infcx, lazily_normalize_ty), ret)]221pub fn orphan_check_trait_ref<Infcx, I, E: Debug>(
222 infcx: &Infcx,
223 trait_ref: ty::TraitRef<I>,
224 in_crate: InCrate,
225 lazily_normalize_ty: impl FnMut(I::Ty) -> Result<I::Ty, E>,
226) -> Result<Result<(), OrphanCheckErr<I, I::Ty>>, E>
227where
228Infcx: InferCtxtLike<Interner = I>,
229 I: Interner,
230 E: Debug,
231{
232if trait_ref.has_param() {
233panic!("orphan check only expects inference variables: {trait_ref:?}");
234 }
235236let mut checker = OrphanChecker::new(infcx, in_crate, lazily_normalize_ty);
237Ok(match trait_ref.visit_with(&mut checker) {
238 ControlFlow::Continue(()) => Err(OrphanCheckErr::NonLocalInputType(checker.non_local_tys)),
239 ControlFlow::Break(residual) => match residual {
240 OrphanCheckEarlyExit::NormalizationFailure(err) => return Err(err),
241 OrphanCheckEarlyExit::UncoveredTyParam(ty) => {
242// Does there exist some local type after the `ParamTy`.
243checker.search_first_local_ty = true;
244let local_ty = match trait_ref.visit_with(&mut checker) {
245 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(local_ty)) => Some(local_ty),
246_ => None,
247 };
248Err(OrphanCheckErr::UncoveredTyParams(UncoveredTyParams {
249 uncovered: ty,
250 local_ty,
251 }))
252 }
253 OrphanCheckEarlyExit::LocalTy(_) => Ok(()),
254 },
255 })
256}
257258struct OrphanChecker<'a, Infcx, I: Interner, F> {
259 infcx: &'a Infcx,
260 in_crate: InCrate,
261 in_self_ty: bool,
262 lazily_normalize_ty: F,
263/// Ignore orphan check failures and exclusively search for the first local type.
264search_first_local_ty: bool,
265 non_local_tys: Vec<(I::Ty, IsFirstInputType)>,
266}
267268impl<'a, Infcx, I, F, E> OrphanChecker<'a, Infcx, I, F>
269where
270Infcx: InferCtxtLike<Interner = I>,
271 I: Interner,
272 F: FnOnce(I::Ty) -> Result<I::Ty, E>,
273{
274fn new(infcx: &'a Infcx, in_crate: InCrate, lazily_normalize_ty: F) -> Self {
275OrphanChecker {
276infcx,
277in_crate,
278 in_self_ty: true,
279lazily_normalize_ty,
280 search_first_local_ty: false,
281 non_local_tys: Vec::new(),
282 }
283 }
284285fn found_non_local_ty(&mut self, t: I::Ty) -> ControlFlow<OrphanCheckEarlyExit<I, E>> {
286self.non_local_tys.push((t, self.in_self_ty.into()));
287 ControlFlow::Continue(())
288 }
289290fn found_uncovered_ty_param(&mut self, ty: I::Ty) -> ControlFlow<OrphanCheckEarlyExit<I, E>> {
291if self.search_first_local_ty {
292return ControlFlow::Continue(());
293 }
294295 ControlFlow::Break(OrphanCheckEarlyExit::UncoveredTyParam(ty))
296 }
297298fn def_id_is_local(&mut self, def_id: impl DefId<I>) -> bool {
299match self.in_crate {
300 InCrate::Local { .. } => def_id.is_local(),
301 InCrate::Remote => false,
302 }
303 }
304}
305306enum OrphanCheckEarlyExit<I: Interner, E> {
307 NormalizationFailure(E),
308 UncoveredTyParam(I::Ty),
309 LocalTy(I::Ty),
310}
311312impl<'a, Infcx, I, F, E> TypeVisitor<I> for OrphanChecker<'a, Infcx, I, F>
313where
314Infcx: InferCtxtLike<Interner = I>,
315 I: Interner,
316 F: FnMut(I::Ty) -> Result<I::Ty, E>,
317{
318type Result = ControlFlow<OrphanCheckEarlyExit<I, E>>;
319320fn visit_region(&mut self, _r: I::Region) -> Self::Result {
321 ControlFlow::Continue(())
322 }
323324fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
325let ty = self.infcx.shallow_resolve(ty);
326let ty = match (self.lazily_normalize_ty)(ty) {
327Ok(norm_ty) if norm_ty.is_ty_var() => ty,
328Ok(norm_ty) => norm_ty,
329Err(err) => return ControlFlow::Break(OrphanCheckEarlyExit::NormalizationFailure(err)),
330 };
331332let result = match ty.kind() {
333 ty::Bool334 | ty::Char335 | ty::Int(..)
336 | ty::Uint(..)
337 | ty::Float(..)
338 | ty::Str339 | ty::Pat(..)
340 | ty::FnPtr(..)
341 | ty::Array(..)
342 | ty::Slice(..)
343 | ty::RawPtr(..)
344 | ty::Never345 | ty::Tuple(..)
346// FIXME(unsafe_binders): Non-local?
347| ty::UnsafeBinder(_) => self.found_non_local_ty(ty),
348349 ty::Param(..) => { ::core::panicking::panic_fmt(format_args!("unexpected ty param")); }panic!("unexpected ty param"),
350351 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => {
352match self.in_crate {
353 InCrate::Local { .. } => self.found_uncovered_ty_param(ty),
354// The inference variable might be unified with a local
355 // type in that remote crate.
356InCrate::Remote => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
357 }
358 }
359360// A rigid alias may normalize to anything.
361 // * If it references an infer var, placeholder or bound ty, it may
362 // normalize to that, so we have to treat it as an uncovered ty param.
363 // * Otherwise it may normalize to any non-type-generic type
364 // be it local or non-local.
365ty::Alias(kind, _) => {
366if ty.has_type_flags(
367 ty::TypeFlags::HAS_TY_PLACEHOLDER368 | ty::TypeFlags::HAS_TY_BOUND369 | ty::TypeFlags::HAS_TY_INFER,
370 ) {
371match self.in_crate {
372 InCrate::Local { mode } => match kind {
373 ty::Projection => {
374if let OrphanCheckMode::Compat = mode {
375 ControlFlow::Continue(())
376 } else {
377self.found_uncovered_ty_param(ty)
378 }
379 }
380_ => self.found_uncovered_ty_param(ty),
381 },
382 InCrate::Remote => {
383// The inference variable might be unified with a local
384 // type in that remote crate.
385ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
386 }
387 }
388 } else {
389// Regarding *opaque types* specifically, we choose to treat them as non-local,
390 // even those that appear within the same crate. This seems somewhat surprising
391 // at first, but makes sense when you consider that opaque types are supposed
392 // to hide the underlying type *within the same crate*. When an opaque type is
393 // used from outside the module where it is declared, it should be impossible to
394 // observe anything about it other than the traits that it implements.
395 //
396 // The alternative would be to look at the underlying type to determine whether
397 // or not the opaque type itself should be considered local.
398 //
399 // However, this could make it a breaking change to switch the underlying hidden
400 // type from a local type to a remote type. This would violate the rule that
401 // opaque types should be completely opaque apart from the traits that they
402 // implement, so we don't use this behavior.
403 // Addendum: Moreover, revealing the underlying type is likely to cause cycle
404 // errors as we rely on coherence / the specialization graph during typeck.
405self.found_non_local_ty(ty)
406 }
407 }
408409// For fundamental types, we just look inside of them.
410ty::Ref(_, ty, _) => ty.visit_with(self),
411 ty::Adt(def, args) => {
412if self.def_id_is_local(def.def_id()) {
413 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
414 } else if def.is_fundamental() {
415args.visit_with(self)
416 } else {
417self.found_non_local_ty(ty)
418 }
419 }
420 ty::Foreign(def_id) => {
421if self.def_id_is_local(def_id) {
422 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
423 } else {
424self.found_non_local_ty(ty)
425 }
426 }
427 ty::Dynamic(tt, ..) => {
428let principal = tt.principal().map(|p| p.def_id());
429if principal.is_some_and(|p| self.def_id_is_local(p)) {
430 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
431 } else {
432self.found_non_local_ty(ty)
433 }
434 }
435 ty::Error(_) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
436437 ty::FnDef(..)
438 | ty::Closure(..)
439 | ty::CoroutineClosure(..)
440 | ty::Coroutine(..)
441 | ty::CoroutineWitness(..) => {
442{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unnameable type in coherence: {0:?}", ty)));
};unreachable!("unnameable type in coherence: {ty:?}");
443 }
444 };
445// A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so
446 // the first type we visit is always the self type.
447self.in_self_ty = false;
448result449 }
450451/// All possible values for a constant parameter already exist
452 /// in the crate defining the trait, so they are always non-local[^1].
453 ///
454 /// Because there's no way to have an impl where the first local
455 /// generic argument is a constant, we also don't have to fail
456 /// the orphan check when encountering a parameter or a generic constant.
457 ///
458 /// This means that we can completely ignore constants during the orphan check.
459 ///
460 /// See `tests/ui/coherence/const-generics-orphan-check-ok.rs` for examples.
461 ///
462 /// [^1]: This might not hold for function pointers or trait objects in the future.
463 /// As these should be quite rare as const arguments and especially rare as impl
464 /// parameters, allowing uncovered const parameters in impls seems more useful
465 /// than allowing `impl<T> Trait<local_fn_ptr, T> for i32` to compile.
466fn visit_const(&mut self, _c: I::Const) -> Self::Result {
467 ControlFlow::Continue(())
468 }
469}