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::{
7 self as ty, InferCtxtLike, Interner, TrivialTypeTraversalImpls, TypeVisitable,
8 TypeVisitableExt, TypeVisitor,
9};
10use tracing::instrument;
11
12/// Whether we do the orphan check relative to this crate or to some remote crate.
13#[derive(Copy, Clone, Debug)]
14pub enum InCrate {
15 Local { mode: OrphanCheckMode },
16 Remote,
17}
18
19#[derive(Copy, Clone, Debug)]
20pub enum OrphanCheckMode {
21 /// Proper orphan check.
22 Proper,
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
31 Compat,
32}
33
34#[derive(Debug, Copy, Clone)]
35pub enum Conflict {
36 Upstream,
37 Downstream,
38}
39
40/// 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.
46#[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>,
50 mut lazily_normalize_ty: impl FnMut(I::Ty) -> Result<I::Ty, E>,
51) -> Result<Result<(), Conflict>, E>
52where
53 Infcx: InferCtxtLike<Interner = I>,
54 I: Interner,
55 E: Debug,
56{
57 if 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.
61 return Ok(Err(Conflict::Downstream));
62 }
63
64 if 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.
70 return Ok(Ok(()));
71 }
72
73 // 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.
81 if 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 {
89 Ok(Ok(()))
90 } else {
91 Ok(Err(Conflict::Upstream))
92 }
93}
94
95pub fn trait_ref_is_local_or_fundamental<I: Interner>(tcx: I, trait_ref: ty::TraitRef<I>) -> bool {
96 trait_ref.def_id.is_local() || tcx.trait_is_fundamental(trait_ref.def_id)
97}
98
99TrivialTypeTraversalImpls! { IsFirstInputType, }
100
101#[derive(Debug, Copy, Clone)]
102pub enum IsFirstInputType {
103 No,
104 Yes,
105}
106
107impl From<bool> for IsFirstInputType {
108 fn from(b: bool) -> IsFirstInputType {
109 match b {
110 false => IsFirstInputType::No,
111 true => IsFirstInputType::Yes,
112 }
113 }
114}
115
116#[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}
121
122#[derive_where(Debug; I: Interner, T: Debug)]
123pub struct UncoveredTyParams<I: Interner, T> {
124 pub uncovered: T,
125 pub local_ty: Option<I::Ty>,
126}
127
128/// 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.
220#[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
228 Infcx: InferCtxtLike<Interner = I>,
229 I: Interner,
230 E: Debug,
231{
232 if trait_ref.has_param() {
233 panic!("orphan check only expects inference variables: {trait_ref:?}");
234 }
235
236 let mut checker = OrphanChecker::new(infcx, in_crate, lazily_normalize_ty);
237 Ok(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`.
243 checker.search_first_local_ty = true;
244 let local_ty = match trait_ref.visit_with(&mut checker) {
245 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(local_ty)) => Some(local_ty),
246 _ => None,
247 };
248 Err(OrphanCheckErr::UncoveredTyParams(UncoveredTyParams {
249 uncovered: ty,
250 local_ty,
251 }))
252 }
253 OrphanCheckEarlyExit::LocalTy(_) => Ok(()),
254 },
255 })
256}
257
258struct 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.
264 search_first_local_ty: bool,
265 non_local_tys: Vec<(I::Ty, IsFirstInputType)>,
266}
267
268impl<'a, Infcx, I, F, E> OrphanChecker<'a, Infcx, I, F>
269where
270 Infcx: InferCtxtLike<Interner = I>,
271 I: Interner,
272 F: FnOnce(I::Ty) -> Result<I::Ty, E>,
273{
274 fn new(infcx: &'a Infcx, in_crate: InCrate, lazily_normalize_ty: F) -> Self {
275 OrphanChecker {
276 infcx,
277 in_crate,
278 in_self_ty: true,
279 lazily_normalize_ty,
280 search_first_local_ty: false,
281 non_local_tys: Vec::new(),
282 }
283 }
284
285 fn found_non_local_ty(&mut self, t: I::Ty) -> ControlFlow<OrphanCheckEarlyExit<I, E>> {
286 self.non_local_tys.push((t, self.in_self_ty.into()));
287 ControlFlow::Continue(())
288 }
289
290 fn found_uncovered_ty_param(&mut self, ty: I::Ty) -> ControlFlow<OrphanCheckEarlyExit<I, E>> {
291 if self.search_first_local_ty {
292 return ControlFlow::Continue(());
293 }
294
295 ControlFlow::Break(OrphanCheckEarlyExit::UncoveredTyParam(ty))
296 }
297
298 fn def_id_is_local(&mut self, def_id: I::DefId) -> bool {
299 match self.in_crate {
300 InCrate::Local { .. } => def_id.is_local(),
301 InCrate::Remote => false,
302 }
303 }
304}
305
306enum OrphanCheckEarlyExit<I: Interner, E> {
307 NormalizationFailure(E),
308 UncoveredTyParam(I::Ty),
309 LocalTy(I::Ty),
310}
311
312impl<'a, Infcx, I, F, E> TypeVisitor<I> for OrphanChecker<'a, Infcx, I, F>
313where
314 Infcx: InferCtxtLike<Interner = I>,
315 I: Interner,
316 F: FnMut(I::Ty) -> Result<I::Ty, E>,
317{
318 type Result = ControlFlow<OrphanCheckEarlyExit<I, E>>;
319
320 fn visit_region(&mut self, _r: I::Region) -> Self::Result {
321 ControlFlow::Continue(())
322 }
323
324 fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
325 let ty = self.infcx.shallow_resolve(ty);
326 let ty = match (self.lazily_normalize_ty)(ty) {
327 Ok(norm_ty) if norm_ty.is_ty_var() => ty,
328 Ok(norm_ty) => norm_ty,
329 Err(err) => return ControlFlow::Break(OrphanCheckEarlyExit::NormalizationFailure(err)),
330 };
331
332 let result = match ty.kind() {
333 ty::Bool
334 | ty::Char
335 | ty::Int(..)
336 | ty::Uint(..)
337 | ty::Float(..)
338 | ty::Str
339 | ty::FnDef(..)
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(..) => 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(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
407 self.found_non_local_ty(ty)
408 }
409 }
410
411 // For fundamental types, we just look inside of them.
412 ty::Ref(_, ty, _) => ty.visit_with(self),
413 ty::Adt(def, args) => {
414 if self.def_id_is_local(def.def_id()) {
415 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
416 } else if def.is_fundamental() {
417 args.visit_with(self)
418 } else {
419 self.found_non_local_ty(ty)
420 }
421 }
422 ty::Foreign(def_id) => {
423 if self.def_id_is_local(def_id) {
424 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
425 } else {
426 self.found_non_local_ty(ty)
427 }
428 }
429 ty::Dynamic(tt, ..) => {
430 let principal = tt.principal().map(|p| p.def_id());
431 if principal.is_some_and(|p| self.def_id_is_local(p)) {
432 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
433 } else {
434 self.found_non_local_ty(ty)
435 }
436 }
437 ty::Error(_) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
438 ty::Closure(did, ..) | ty::CoroutineClosure(did, ..) | ty::Coroutine(did, ..) => {
439 if self.def_id_is_local(did) {
440 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
441 } else {
442 self.found_non_local_ty(ty)
443 }
444 }
445 // This should only be created when checking whether we have to check whether some
446 // auto trait impl applies. There will never be multiple impls, so we can just
447 // act as if it were a local type here.
448 ty::CoroutineWitness(..) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
449 };
450 // A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so
451 // the first type we visit is always the self type.
452 self.in_self_ty = false;
453 result
454 }
455
456 /// All possible values for a constant parameter already exist
457 /// in the crate defining the trait, so they are always non-local[^1].
458 ///
459 /// Because there's no way to have an impl where the first local
460 /// generic argument is a constant, we also don't have to fail
461 /// the orphan check when encountering a parameter or a generic constant.
462 ///
463 /// This means that we can completely ignore constants during the orphan check.
464 ///
465 /// See `tests/ui/coherence/const-generics-orphan-check-ok.rs` for examples.
466 ///
467 /// [^1]: This might not hold for function pointers or trait objects in the future.
468 /// As these should be quite rare as const arguments and especially rare as impl
469 /// parameters, allowing uncovered const parameters in impls seems more useful
470 /// than allowing `impl<T> Trait<local_fn_ptr, T> for i32` to compile.
471 fn visit_const(&mut self, _c: I::Const) -> Self::Result {
472 ControlFlow::Continue(())
473 }
474}