• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
2 //! how this works.
3 //!
4 //! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
5 //! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
6 
7 use crate::infer::outlives::env::OutlivesEnvironment;
8 use crate::infer::InferOk;
9 use crate::traits::outlives_bounds::InferCtxtExt as _;
10 use crate::traits::select::IntercrateAmbiguityCause;
11 use crate::traits::util::impl_subject_and_oblig;
12 use crate::traits::SkipLeakCheck;
13 use crate::traits::{
14     self, Obligation, ObligationCause, ObligationCtxt, PredicateObligation, PredicateObligations,
15     SelectionContext,
16 };
17 use rustc_data_structures::fx::FxIndexSet;
18 use rustc_errors::Diagnostic;
19 use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
20 use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
21 use rustc_infer::traits::util;
22 use rustc_middle::traits::specialization_graph::OverlapMode;
23 use rustc_middle::traits::DefiningAnchor;
24 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
25 use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt};
26 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor};
27 use rustc_span::symbol::sym;
28 use rustc_span::DUMMY_SP;
29 use std::fmt::Debug;
30 use std::iter;
31 use std::ops::ControlFlow;
32 
33 use super::query::evaluate_obligation::InferCtxtExt;
34 use super::NormalizeExt;
35 
36 /// Whether we do the orphan check relative to this crate or
37 /// to some remote crate.
38 #[derive(Copy, Clone, Debug)]
39 enum InCrate {
40     Local,
41     Remote,
42 }
43 
44 #[derive(Debug, Copy, Clone)]
45 pub enum Conflict {
46     Upstream,
47     Downstream,
48 }
49 
50 pub struct OverlapResult<'tcx> {
51     pub impl_header: ty::ImplHeader<'tcx>,
52     pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause>,
53 
54     /// `true` if the overlap might've been permitted before the shift
55     /// to universes.
56     pub involves_placeholder: bool,
57 }
58 
add_placeholder_note(err: &mut Diagnostic)59 pub fn add_placeholder_note(err: &mut Diagnostic) {
60     err.note(
61         "this behavior recently changed as a result of a bug fix; \
62          see rust-lang/rust#56105 for details",
63     );
64 }
65 
66 #[derive(Debug, Clone, Copy)]
67 enum TrackAmbiguityCauses {
68     Yes,
69     No,
70 }
71 
72 impl TrackAmbiguityCauses {
is_yes(self) -> bool73     fn is_yes(self) -> bool {
74         match self {
75             TrackAmbiguityCauses::Yes => true,
76             TrackAmbiguityCauses::No => false,
77         }
78     }
79 }
80 
81 /// If there are types that satisfy both impls, returns `Some`
82 /// with a suitably-freshened `ImplHeader` with those types
83 /// substituted. Otherwise, returns `None`.
84 #[instrument(skip(tcx, skip_leak_check), level = "debug")]
overlapping_impls( tcx: TyCtxt<'_>, impl1_def_id: DefId, impl2_def_id: DefId, skip_leak_check: SkipLeakCheck, overlap_mode: OverlapMode, ) -> Option<OverlapResult<'_>>85 pub fn overlapping_impls(
86     tcx: TyCtxt<'_>,
87     impl1_def_id: DefId,
88     impl2_def_id: DefId,
89     skip_leak_check: SkipLeakCheck,
90     overlap_mode: OverlapMode,
91 ) -> Option<OverlapResult<'_>> {
92     // Before doing expensive operations like entering an inference context, do
93     // a quick check via fast_reject to tell if the impl headers could possibly
94     // unify.
95     let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsCandidateKey };
96     let impl1_ref = tcx.impl_trait_ref(impl1_def_id);
97     let impl2_ref = tcx.impl_trait_ref(impl2_def_id);
98     let may_overlap = match (impl1_ref, impl2_ref) {
99         (Some(a), Some(b)) => {
100             drcx.substs_refs_may_unify(a.skip_binder().substs, b.skip_binder().substs)
101         }
102         (None, None) => {
103             let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
104             let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
105             drcx.types_may_unify(self_ty1, self_ty2)
106         }
107         _ => bug!("unexpected impls: {impl1_def_id:?} {impl2_def_id:?}"),
108     };
109 
110     if !may_overlap {
111         // Some types involved are definitely different, so the impls couldn't possibly overlap.
112         debug!("overlapping_impls: fast_reject early-exit");
113         return None;
114     }
115 
116     let _overlap_with_bad_diagnostics = overlap(
117         tcx,
118         TrackAmbiguityCauses::No,
119         skip_leak_check,
120         impl1_def_id,
121         impl2_def_id,
122         overlap_mode,
123     )?;
124 
125     // In the case where we detect an error, run the check again, but
126     // this time tracking intercrate ambiguity causes for better
127     // diagnostics. (These take time and can lead to false errors.)
128     let overlap = overlap(
129         tcx,
130         TrackAmbiguityCauses::Yes,
131         skip_leak_check,
132         impl1_def_id,
133         impl2_def_id,
134         overlap_mode,
135     )
136     .unwrap();
137     Some(overlap)
138 }
139 
with_fresh_ty_vars<'cx, 'tcx>( selcx: &mut SelectionContext<'cx, 'tcx>, param_env: ty::ParamEnv<'tcx>, impl_def_id: DefId, ) -> ty::ImplHeader<'tcx>140 fn with_fresh_ty_vars<'cx, 'tcx>(
141     selcx: &mut SelectionContext<'cx, 'tcx>,
142     param_env: ty::ParamEnv<'tcx>,
143     impl_def_id: DefId,
144 ) -> ty::ImplHeader<'tcx> {
145     let tcx = selcx.tcx();
146     let impl_substs = selcx.infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
147 
148     let header = ty::ImplHeader {
149         impl_def_id,
150         self_ty: tcx.type_of(impl_def_id).subst(tcx, impl_substs),
151         trait_ref: tcx.impl_trait_ref(impl_def_id).map(|i| i.subst(tcx, impl_substs)),
152         predicates: tcx
153             .predicates_of(impl_def_id)
154             .instantiate(tcx, impl_substs)
155             .iter()
156             .map(|(c, _)| c.as_predicate())
157             .collect(),
158     };
159 
160     let InferOk { value: mut header, obligations } =
161         selcx.infcx.at(&ObligationCause::dummy(), param_env).normalize(header);
162 
163     header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
164     header
165 }
166 
167 /// Can both impl `a` and impl `b` be satisfied by a common type (including
168 /// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
169 #[instrument(level = "debug", skip(tcx))]
overlap<'tcx>( tcx: TyCtxt<'tcx>, track_ambiguity_causes: TrackAmbiguityCauses, skip_leak_check: SkipLeakCheck, impl1_def_id: DefId, impl2_def_id: DefId, overlap_mode: OverlapMode, ) -> Option<OverlapResult<'tcx>>170 fn overlap<'tcx>(
171     tcx: TyCtxt<'tcx>,
172     track_ambiguity_causes: TrackAmbiguityCauses,
173     skip_leak_check: SkipLeakCheck,
174     impl1_def_id: DefId,
175     impl2_def_id: DefId,
176     overlap_mode: OverlapMode,
177 ) -> Option<OverlapResult<'tcx>> {
178     if overlap_mode.use_negative_impl() {
179         if impl_intersection_has_negative_obligation(tcx, impl1_def_id, impl2_def_id)
180             || impl_intersection_has_negative_obligation(tcx, impl2_def_id, impl1_def_id)
181         {
182             return None;
183         }
184     }
185 
186     let infcx = tcx
187         .infer_ctxt()
188         .with_opaque_type_inference(DefiningAnchor::Bubble)
189         .skip_leak_check(skip_leak_check.is_yes())
190         .intercrate(true)
191         .with_next_trait_solver(tcx.next_trait_solver_in_coherence())
192         .build();
193     let selcx = &mut SelectionContext::new(&infcx);
194     if track_ambiguity_causes.is_yes() {
195         selcx.enable_tracking_intercrate_ambiguity_causes();
196     }
197 
198     // For the purposes of this check, we don't bring any placeholder
199     // types into scope; instead, we replace the generic types with
200     // fresh type variables, and hence we do our evaluations in an
201     // empty environment.
202     let param_env = ty::ParamEnv::empty();
203 
204     let impl1_header = with_fresh_ty_vars(selcx, param_env, impl1_def_id);
205     let impl2_header = with_fresh_ty_vars(selcx, param_env, impl2_def_id);
206 
207     // Equate the headers to find their intersection (the general type, with infer vars,
208     // that may apply both impls).
209     let equate_obligations = equate_impl_headers(selcx.infcx, &impl1_header, &impl2_header)?;
210     debug!("overlap: unification check succeeded");
211 
212     if overlap_mode.use_implicit_negative()
213         && impl_intersection_has_impossible_obligation(
214             selcx,
215             param_env,
216             &impl1_header,
217             impl2_header,
218             equate_obligations,
219         )
220     {
221         return None;
222     }
223 
224     // We toggle the `leak_check` by using `skip_leak_check` when constructing the
225     // inference context, so this may be a noop.
226     if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
227         debug!("overlap: leak check failed");
228         return None;
229     }
230 
231     let intercrate_ambiguity_causes = selcx.take_intercrate_ambiguity_causes();
232     debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
233     let involves_placeholder = infcx
234         .inner
235         .borrow_mut()
236         .unwrap_region_constraints()
237         .data()
238         .constraints
239         .iter()
240         .any(|c| c.0.involves_placeholders());
241 
242     let impl_header = selcx.infcx.resolve_vars_if_possible(impl1_header);
243     Some(OverlapResult { impl_header, intercrate_ambiguity_causes, involves_placeholder })
244 }
245 
246 #[instrument(level = "debug", skip(infcx), ret)]
equate_impl_headers<'tcx>( infcx: &InferCtxt<'tcx>, impl1: &ty::ImplHeader<'tcx>, impl2: &ty::ImplHeader<'tcx>, ) -> Option<PredicateObligations<'tcx>>247 fn equate_impl_headers<'tcx>(
248     infcx: &InferCtxt<'tcx>,
249     impl1: &ty::ImplHeader<'tcx>,
250     impl2: &ty::ImplHeader<'tcx>,
251 ) -> Option<PredicateObligations<'tcx>> {
252     let result = match (impl1.trait_ref, impl2.trait_ref) {
253         (Some(impl1_ref), Some(impl2_ref)) => infcx
254             .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
255             .eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
256         (None, None) => infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
257             DefineOpaqueTypes::Yes,
258             impl1.self_ty,
259             impl2.self_ty,
260         ),
261         _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
262     };
263 
264     result.map(|infer_ok| infer_ok.obligations).ok()
265 }
266 
267 /// Check if both impls can be satisfied by a common type by considering whether
268 /// any of either impl's obligations is not known to hold.
269 ///
270 /// For example, given these two impls:
271 ///     `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
272 ///     `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
273 ///
274 /// After replacing both impl headers with inference vars (which happens before
275 /// this function is called), we get:
276 ///     `Box<dyn Error>: From<MyLocalType>`
277 ///     `Box<dyn Error>: From<?E>`
278 ///
279 /// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
280 /// never holds in intercrate mode since a local impl does not exist, and a
281 /// downstream impl cannot be added -- therefore can consider the intersection
282 /// of the two impls above to be empty.
283 ///
284 /// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
impl_intersection_has_impossible_obligation<'cx, 'tcx>( selcx: &mut SelectionContext<'cx, 'tcx>, param_env: ty::ParamEnv<'tcx>, impl1_header: &ty::ImplHeader<'tcx>, impl2_header: ty::ImplHeader<'tcx>, obligations: PredicateObligations<'tcx>, ) -> bool285 fn impl_intersection_has_impossible_obligation<'cx, 'tcx>(
286     selcx: &mut SelectionContext<'cx, 'tcx>,
287     param_env: ty::ParamEnv<'tcx>,
288     impl1_header: &ty::ImplHeader<'tcx>,
289     impl2_header: ty::ImplHeader<'tcx>,
290     obligations: PredicateObligations<'tcx>,
291 ) -> bool {
292     let infcx = selcx.infcx;
293 
294     let obligation_guaranteed_to_fail = move |obligation: &PredicateObligation<'tcx>| {
295         if infcx.next_trait_solver() {
296             infcx.evaluate_obligation(obligation).map_or(false, |result| !result.may_apply())
297         } else {
298             // We use `evaluate_root_obligation` to correctly track
299             // intercrate ambiguity clauses. We do not need this in the
300             // new solver.
301             selcx.evaluate_root_obligation(obligation).map_or(
302                 false, // Overflow has occurred, and treat the obligation as possibly holding.
303                 |result| !result.may_apply(),
304             )
305         }
306     };
307 
308     let opt_failing_obligation = [&impl1_header.predicates, &impl2_header.predicates]
309         .into_iter()
310         .flatten()
311         .map(|&predicate| {
312             Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate)
313         })
314         .chain(obligations)
315         .find(obligation_guaranteed_to_fail);
316 
317     if let Some(failing_obligation) = opt_failing_obligation {
318         debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
319         true
320     } else {
321         false
322     }
323 }
324 
325 /// Check if both impls can be satisfied by a common type by considering whether
326 /// any of first impl's obligations is known not to hold *via a negative predicate*.
327 ///
328 /// For example, given these two impls:
329 ///     `struct MyCustomBox<T: ?Sized>(Box<T>);`
330 ///     `impl From<&str> for MyCustomBox<dyn Error>` (in my crate)
331 ///     `impl<E> From<E> for MyCustomBox<dyn Error> where E: Error` (in my crate)
332 ///
333 /// After replacing the second impl's header with inference vars, we get:
334 ///     `MyCustomBox<dyn Error>: From<&str>`
335 ///     `MyCustomBox<dyn Error>: From<?E>`
336 ///
337 /// This gives us `?E = &str`. We then try to prove the first impl's predicates
338 /// after negating, giving us `&str: !Error`. This is a negative impl provided by
339 /// libstd, and therefore we can guarantee for certain that libstd will never add
340 /// a positive impl for `&str: Error` (without it being a breaking change).
impl_intersection_has_negative_obligation( tcx: TyCtxt<'_>, impl1_def_id: DefId, impl2_def_id: DefId, ) -> bool341 fn impl_intersection_has_negative_obligation(
342     tcx: TyCtxt<'_>,
343     impl1_def_id: DefId,
344     impl2_def_id: DefId,
345 ) -> bool {
346     debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
347 
348     // Create an infcx, taking the predicates of impl1 as assumptions:
349     let infcx = tcx.infer_ctxt().build();
350     // create a parameter environment corresponding to a (placeholder) instantiation of impl1
351     let impl_env = tcx.param_env(impl1_def_id);
352     let subject1 = match traits::fully_normalize(
353         &infcx,
354         ObligationCause::dummy(),
355         impl_env,
356         tcx.impl_subject(impl1_def_id).subst_identity(),
357     ) {
358         Ok(s) => s,
359         Err(err) => {
360             tcx.sess.delay_span_bug(
361                 tcx.def_span(impl1_def_id),
362                 format!("failed to fully normalize {:?}: {:?}", impl1_def_id, err),
363             );
364             return false;
365         }
366     };
367 
368     // Attempt to prove that impl2 applies, given all of the above.
369     let selcx = &mut SelectionContext::new(&infcx);
370     let impl2_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl2_def_id);
371     let (subject2, normalization_obligations) =
372         impl_subject_and_oblig(selcx, impl_env, impl2_def_id, impl2_substs, |_, _| {
373             ObligationCause::dummy()
374         });
375 
376     // do the impls unify? If not, then it's not currently possible to prove any
377     // obligations about their intersection.
378     let Ok(InferOk { obligations: equate_obligations, .. }) =
379         infcx.at(&ObligationCause::dummy(), impl_env).eq(DefineOpaqueTypes::No,subject1, subject2)
380     else {
381         debug!("explicit_disjoint: {:?} does not unify with {:?}", subject1, subject2);
382         return false;
383     };
384 
385     for obligation in normalization_obligations.into_iter().chain(equate_obligations) {
386         if negative_impl_exists(&infcx, &obligation, impl1_def_id) {
387             debug!("overlap: obligation unsatisfiable {:?}", obligation);
388             return true;
389         }
390     }
391 
392     false
393 }
394 
395 /// Try to prove that a negative impl exist for the obligation or its supertraits.
396 ///
397 /// If such a negative impl exists, then the obligation definitely must not hold
398 /// due to coherence, even if it's not necessarily "knowable" in this crate. Any
399 /// valid impl downstream would not be able to exist due to the overlapping
400 /// negative impl.
401 #[instrument(level = "debug", skip(infcx))]
negative_impl_exists<'tcx>( infcx: &InferCtxt<'tcx>, o: &PredicateObligation<'tcx>, body_def_id: DefId, ) -> bool402 fn negative_impl_exists<'tcx>(
403     infcx: &InferCtxt<'tcx>,
404     o: &PredicateObligation<'tcx>,
405     body_def_id: DefId,
406 ) -> bool {
407     // Try to prove a negative obligation exists for super predicates
408     for pred in util::elaborate(infcx.tcx, iter::once(o.predicate)) {
409         if prove_negated_obligation(infcx.fork(), &o.with(infcx.tcx, pred), body_def_id) {
410             return true;
411         }
412     }
413 
414     false
415 }
416 
417 #[instrument(level = "debug", skip(infcx))]
prove_negated_obligation<'tcx>( infcx: InferCtxt<'tcx>, o: &PredicateObligation<'tcx>, body_def_id: DefId, ) -> bool418 fn prove_negated_obligation<'tcx>(
419     infcx: InferCtxt<'tcx>,
420     o: &PredicateObligation<'tcx>,
421     body_def_id: DefId,
422 ) -> bool {
423     let tcx = infcx.tcx;
424 
425     let Some(o) = o.flip_polarity(tcx) else {
426         return false;
427     };
428 
429     let param_env = o.param_env;
430     let ocx = ObligationCtxt::new(&infcx);
431     ocx.register_obligation(o);
432     let errors = ocx.select_all_or_error();
433     if !errors.is_empty() {
434         return false;
435     }
436 
437     let body_def_id = body_def_id.as_local().unwrap_or(CRATE_DEF_ID);
438 
439     let ocx = ObligationCtxt::new(&infcx);
440     let Ok(wf_tys) = ocx.assumed_wf_types(param_env, body_def_id)
441     else {
442         return false;
443     };
444 
445     let outlives_env = OutlivesEnvironment::with_bounds(
446         param_env,
447         infcx.implied_bounds_tys(param_env, body_def_id, wf_tys),
448     );
449     infcx.resolve_regions(&outlives_env).is_empty()
450 }
451 
452 /// Returns whether all impls which would apply to the `trait_ref`
453 /// e.g. `Ty: Trait<Arg>` are already known in the local crate.
454 ///
455 /// This both checks whether any downstream or sibling crates could
456 /// implement it and whether an upstream crate can add this impl
457 /// without breaking backwards compatibility.
458 #[instrument(level = "debug", skip(tcx), ret)]
trait_ref_is_knowable<'tcx>( tcx: TyCtxt<'tcx>, trait_ref: ty::TraitRef<'tcx>, ) -> Result<(), Conflict>459 pub fn trait_ref_is_knowable<'tcx>(
460     tcx: TyCtxt<'tcx>,
461     trait_ref: ty::TraitRef<'tcx>,
462 ) -> Result<(), Conflict> {
463     if Some(trait_ref.def_id) == tcx.lang_items().fn_ptr_trait() {
464         // The only types implementing `FnPtr` are function pointers,
465         // so if there's no impl of `FnPtr` in the current crate,
466         // then such an impl will never be added in the future.
467         return Ok(());
468     }
469 
470     if orphan_check_trait_ref(trait_ref, InCrate::Remote).is_ok() {
471         // A downstream or cousin crate is allowed to implement some
472         // substitution of this trait-ref.
473         return Err(Conflict::Downstream);
474     }
475 
476     if trait_ref_is_local_or_fundamental(tcx, trait_ref) {
477         // This is a local or fundamental trait, so future-compatibility
478         // is no concern. We know that downstream/cousin crates are not
479         // allowed to implement a substitution of this trait ref, which
480         // means impls could only come from dependencies of this crate,
481         // which we already know about.
482         return Ok(());
483     }
484 
485     // This is a remote non-fundamental trait, so if another crate
486     // can be the "final owner" of a substitution of this trait-ref,
487     // they are allowed to implement it future-compatibly.
488     //
489     // However, if we are a final owner, then nobody else can be,
490     // and if we are an intermediate owner, then we don't care
491     // about future-compatibility, which means that we're OK if
492     // we are an owner.
493     if orphan_check_trait_ref(trait_ref, InCrate::Local).is_ok() {
494         Ok(())
495     } else {
496         Err(Conflict::Upstream)
497     }
498 }
499 
trait_ref_is_local_or_fundamental<'tcx>( tcx: TyCtxt<'tcx>, trait_ref: ty::TraitRef<'tcx>, ) -> bool500 pub fn trait_ref_is_local_or_fundamental<'tcx>(
501     tcx: TyCtxt<'tcx>,
502     trait_ref: ty::TraitRef<'tcx>,
503 ) -> bool {
504     trait_ref.def_id.krate == LOCAL_CRATE || tcx.has_attr(trait_ref.def_id, sym::fundamental)
505 }
506 
507 #[derive(Debug)]
508 pub enum OrphanCheckErr<'tcx> {
509     NonLocalInputType(Vec<(Ty<'tcx>, bool /* Is this the first input type? */)>),
510     UncoveredTy(Ty<'tcx>, Option<Ty<'tcx>>),
511 }
512 
513 /// Checks the coherence orphan rules. `impl_def_id` should be the
514 /// `DefId` of a trait impl. To pass, either the trait must be local, or else
515 /// two conditions must be satisfied:
516 ///
517 /// 1. All type parameters in `Self` must be "covered" by some local type constructor.
518 /// 2. Some local type must appear in `Self`.
519 #[instrument(level = "debug", skip(tcx), ret)]
orphan_check(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Result<(), OrphanCheckErr<'_>>520 pub fn orphan_check(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Result<(), OrphanCheckErr<'_>> {
521     // We only except this routine to be invoked on implementations
522     // of a trait, not inherent implementations.
523     let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().subst_identity();
524     debug!(?trait_ref);
525 
526     // If the *trait* is local to the crate, ok.
527     if trait_ref.def_id.is_local() {
528         debug!("trait {:?} is local to current crate", trait_ref.def_id);
529         return Ok(());
530     }
531 
532     orphan_check_trait_ref(trait_ref, InCrate::Local)
533 }
534 
535 /// Checks whether a trait-ref is potentially implementable by a crate.
536 ///
537 /// The current rule is that a trait-ref orphan checks in a crate C:
538 ///
539 /// 1. Order the parameters in the trait-ref in subst order - Self first,
540 ///    others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
541 /// 2. Of these type parameters, there is at least one type parameter
542 ///    in which, walking the type as a tree, you can reach a type local
543 ///    to C where all types in-between are fundamental types. Call the
544 ///    first such parameter the "local key parameter".
545 ///     - e.g., `Box<LocalType>` is OK, because you can visit LocalType
546 ///       going through `Box`, which is fundamental.
547 ///     - similarly, `FundamentalPair<Vec<()>, Box<LocalType>>` is OK for
548 ///       the same reason.
549 ///     - but (knowing that `Vec<T>` is non-fundamental, and assuming it's
550 ///       not local), `Vec<LocalType>` is bad, because `Vec<->` is between
551 ///       the local type and the type parameter.
552 /// 3. Before this local type, no generic type parameter of the impl must
553 ///    be reachable through fundamental types.
554 ///     - e.g. `impl<T> Trait<LocalType> for Vec<T>` is fine, as `Vec` is not fundamental.
555 ///     - while `impl<T> Trait<LocalType> for Box<T>` results in an error, as `T` is
556 ///       reachable through the fundamental type `Box`.
557 /// 4. Every type in the local key parameter not known in C, going
558 ///    through the parameter's type tree, must appear only as a subtree of
559 ///    a type local to C, with only fundamental types between the type
560 ///    local to C and the local key parameter.
561 ///     - e.g., `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
562 ///     is bad, because the only local type with `T` as a subtree is
563 ///     `LocalType<T>`, and `Vec<->` is between it and the type parameter.
564 ///     - similarly, `FundamentalPair<LocalType<T>, T>` is bad, because
565 ///     the second occurrence of `T` is not a subtree of *any* local type.
566 ///     - however, `LocalType<Vec<T>>` is OK, because `T` is a subtree of
567 ///     `LocalType<Vec<T>>`, which is local and has no types between it and
568 ///     the type parameter.
569 ///
570 /// The orphan rules actually serve several different purposes:
571 ///
572 /// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where
573 ///    every type local to one crate is unknown in the other) can't implement
574 ///    the same trait-ref. This follows because it can be seen that no such
575 ///    type can orphan-check in 2 such crates.
576 ///
577 ///    To check that a local impl follows the orphan rules, we check it in
578 ///    InCrate::Local mode, using type parameters for the "generic" types.
579 ///
580 /// 2. They ground negative reasoning for coherence. If a user wants to
581 ///    write both a conditional blanket impl and a specific impl, we need to
582 ///    make sure they do not overlap. For example, if we write
583 ///    ```ignore (illustrative)
584 ///    impl<T> IntoIterator for Vec<T>
585 ///    impl<T: Iterator> IntoIterator for T
586 ///    ```
587 ///    We need to be able to prove that `Vec<$0>: !Iterator` for every type $0.
588 ///    We can observe that this holds in the current crate, but we need to make
589 ///    sure this will also hold in all unknown crates (both "independent" crates,
590 ///    which we need for link-safety, and also child crates, because we don't want
591 ///    child crates to get error for impl conflicts in a *dependency*).
592 ///
593 ///    For that, we only allow negative reasoning if, for every assignment to the
594 ///    inference variables, every unknown crate would get an orphan error if they
595 ///    try to implement this trait-ref. To check for this, we use InCrate::Remote
596 ///    mode. That is sound because we already know all the impls from known crates.
597 ///
598 /// 3. For non-`#[fundamental]` traits, they guarantee that parent crates can
599 ///    add "non-blanket" impls without breaking negative reasoning in dependent
600 ///    crates. This is the "rebalancing coherence" (RFC 1023) restriction.
601 ///
602 ///    For that, we only a allow crate to perform negative reasoning on
603 ///    non-local-non-`#[fundamental]` only if there's a local key parameter as per (2).
604 ///
605 ///    Because we never perform negative reasoning generically (coherence does
606 ///    not involve type parameters), this can be interpreted as doing the full
607 ///    orphan check (using InCrate::Local mode), substituting non-local known
608 ///    types for all inference variables.
609 ///
610 ///    This allows for crates to future-compatibly add impls as long as they
611 ///    can't apply to types with a key parameter in a child crate - applying
612 ///    the rules, this basically means that every type parameter in the impl
613 ///    must appear behind a non-fundamental type (because this is not a
614 ///    type-system requirement, crate owners might also go for "semantic
615 ///    future-compatibility" involving things such as sealed traits, but
616 ///    the above requirement is sufficient, and is necessary in "open world"
617 ///    cases).
618 ///
619 /// Note that this function is never called for types that have both type
620 /// parameters and inference variables.
621 #[instrument(level = "trace", ret)]
orphan_check_trait_ref<'tcx>( trait_ref: ty::TraitRef<'tcx>, in_crate: InCrate, ) -> Result<(), OrphanCheckErr<'tcx>>622 fn orphan_check_trait_ref<'tcx>(
623     trait_ref: ty::TraitRef<'tcx>,
624     in_crate: InCrate,
625 ) -> Result<(), OrphanCheckErr<'tcx>> {
626     if trait_ref.has_infer() && trait_ref.has_param() {
627         bug!(
628             "can't orphan check a trait ref with both params and inference variables {:?}",
629             trait_ref
630         );
631     }
632 
633     let mut checker = OrphanChecker::new(in_crate);
634     match trait_ref.visit_with(&mut checker) {
635         ControlFlow::Continue(()) => Err(OrphanCheckErr::NonLocalInputType(checker.non_local_tys)),
636         ControlFlow::Break(OrphanCheckEarlyExit::ParamTy(ty)) => {
637             // Does there exist some local type after the `ParamTy`.
638             checker.search_first_local_ty = true;
639             if let Some(OrphanCheckEarlyExit::LocalTy(local_ty)) =
640                 trait_ref.visit_with(&mut checker).break_value()
641             {
642                 Err(OrphanCheckErr::UncoveredTy(ty, Some(local_ty)))
643             } else {
644                 Err(OrphanCheckErr::UncoveredTy(ty, None))
645             }
646         }
647         ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(_)) => Ok(()),
648     }
649 }
650 
651 struct OrphanChecker<'tcx> {
652     in_crate: InCrate,
653     in_self_ty: bool,
654     /// Ignore orphan check failures and exclusively search for the first
655     /// local type.
656     search_first_local_ty: bool,
657     non_local_tys: Vec<(Ty<'tcx>, bool)>,
658 }
659 
660 impl<'tcx> OrphanChecker<'tcx> {
new(in_crate: InCrate) -> Self661     fn new(in_crate: InCrate) -> Self {
662         OrphanChecker {
663             in_crate,
664             in_self_ty: true,
665             search_first_local_ty: false,
666             non_local_tys: Vec::new(),
667         }
668     }
669 
found_non_local_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx>>670     fn found_non_local_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx>> {
671         self.non_local_tys.push((t, self.in_self_ty));
672         ControlFlow::Continue(())
673     }
674 
found_param_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx>>675     fn found_param_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx>> {
676         if self.search_first_local_ty {
677             ControlFlow::Continue(())
678         } else {
679             ControlFlow::Break(OrphanCheckEarlyExit::ParamTy(t))
680         }
681     }
682 
def_id_is_local(&mut self, def_id: DefId) -> bool683     fn def_id_is_local(&mut self, def_id: DefId) -> bool {
684         match self.in_crate {
685             InCrate::Local => def_id.is_local(),
686             InCrate::Remote => false,
687         }
688     }
689 }
690 
691 enum OrphanCheckEarlyExit<'tcx> {
692     ParamTy(Ty<'tcx>),
693     LocalTy(Ty<'tcx>),
694 }
695 
696 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for OrphanChecker<'tcx> {
697     type BreakTy = OrphanCheckEarlyExit<'tcx>;
visit_region(&mut self, _r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy>698     fn visit_region(&mut self, _r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
699         ControlFlow::Continue(())
700     }
701 
visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy>702     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
703         let result = match *ty.kind() {
704             ty::Bool
705             | ty::Char
706             | ty::Int(..)
707             | ty::Uint(..)
708             | ty::Float(..)
709             | ty::Str
710             | ty::FnDef(..)
711             | ty::FnPtr(_)
712             | ty::Array(..)
713             | ty::Slice(..)
714             | ty::RawPtr(..)
715             | ty::Never
716             | ty::Tuple(..)
717             | ty::Alias(ty::Projection | ty::Inherent | ty::Weak, ..) => {
718                 self.found_non_local_ty(ty)
719             }
720 
721             ty::Param(..) => self.found_param_ty(ty),
722 
723             ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => match self.in_crate {
724                 InCrate::Local => self.found_non_local_ty(ty),
725                 // The inference variable might be unified with a local
726                 // type in that remote crate.
727                 InCrate::Remote => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
728             },
729 
730             // For fundamental types, we just look inside of them.
731             ty::Ref(_, ty, _) => ty.visit_with(self),
732             ty::Adt(def, substs) => {
733                 if self.def_id_is_local(def.did()) {
734                     ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
735                 } else if def.is_fundamental() {
736                     substs.visit_with(self)
737                 } else {
738                     self.found_non_local_ty(ty)
739                 }
740             }
741             ty::Foreign(def_id) => {
742                 if self.def_id_is_local(def_id) {
743                     ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
744                 } else {
745                     self.found_non_local_ty(ty)
746                 }
747             }
748             ty::Dynamic(tt, ..) => {
749                 let principal = tt.principal().map(|p| p.def_id());
750                 if principal.is_some_and(|p| self.def_id_is_local(p)) {
751                     ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
752                 } else {
753                     self.found_non_local_ty(ty)
754                 }
755             }
756             ty::Error(_) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
757             ty::Closure(did, ..) | ty::Generator(did, ..) => {
758                 if self.def_id_is_local(did) {
759                     ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
760                 } else {
761                     self.found_non_local_ty(ty)
762                 }
763             }
764             // This should only be created when checking whether we have to check whether some
765             // auto trait impl applies. There will never be multiple impls, so we can just
766             // act as if it were a local type here.
767             ty::GeneratorWitness(_) | ty::GeneratorWitnessMIR(..) => {
768                 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
769             }
770             ty::Alias(ty::Opaque, ..) => {
771                 // This merits some explanation.
772                 // Normally, opaque types are not involved when performing
773                 // coherence checking, since it is illegal to directly
774                 // implement a trait on an opaque type. However, we might
775                 // end up looking at an opaque type during coherence checking
776                 // if an opaque type gets used within another type (e.g. as
777                 // the type of a field) when checking for auto trait or `Sized`
778                 // impls. This requires us to decide whether or not an opaque
779                 // type should be considered 'local' or not.
780                 //
781                 // We choose to treat all opaque types as non-local, even
782                 // those that appear within the same crate. This seems
783                 // somewhat surprising at first, but makes sense when
784                 // you consider that opaque types are supposed to hide
785                 // the underlying type *within the same crate*. When an
786                 // opaque type is used from outside the module
787                 // where it is declared, it should be impossible to observe
788                 // anything about it other than the traits that it implements.
789                 //
790                 // The alternative would be to look at the underlying type
791                 // to determine whether or not the opaque type itself should
792                 // be considered local. However, this could make it a breaking change
793                 // to switch the underlying ('defining') type from a local type
794                 // to a remote type. This would violate the rule that opaque
795                 // types should be completely opaque apart from the traits
796                 // that they implement, so we don't use this behavior.
797                 self.found_non_local_ty(ty)
798             }
799         };
800         // A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so
801         // the first type we visit is always the self type.
802         self.in_self_ty = false;
803         result
804     }
805 
806     /// All possible values for a constant parameter already exist
807     /// in the crate defining the trait, so they are always non-local[^1].
808     ///
809     /// Because there's no way to have an impl where the first local
810     /// generic argument is a constant, we also don't have to fail
811     /// the orphan check when encountering a parameter or a generic constant.
812     ///
813     /// This means that we can completely ignore constants during the orphan check.
814     ///
815     /// See `tests/ui/coherence/const-generics-orphan-check-ok.rs` for examples.
816     ///
817     /// [^1]: This might not hold for function pointers or trait objects in the future.
818     /// As these should be quite rare as const arguments and especially rare as impl
819     /// parameters, allowing uncovered const parameters in impls seems more useful
820     /// than allowing `impl<T> Trait<local_fn_ptr, T> for i32` to compile.
visit_const(&mut self, _c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy>821     fn visit_const(&mut self, _c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
822         ControlFlow::Continue(())
823     }
824 }
825