Skip to main content

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