rustc_next_trait_solver/
coherence.rs

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