1 //! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
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
7 use crate::infer::outlives::env::OutlivesEnvironment;
8 use crate::infer::{CombinedSnapshot, 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;
14 self, Normalized, Obligation, ObligationCause, ObligationCtxt, PredicateObligation,
15 PredicateObligations, SelectionContext,
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_hir::CRATE_HIR_ID;
21 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
22 use rustc_infer::traits::util;
23 use rustc_middle::traits::specialization_graph::OverlapMode;
24 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
25 use rustc_middle::ty::visit::TypeVisitable;
26 use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt, TypeVisitor};
27 use rustc_span::symbol::sym;
28 use rustc_span::DUMMY_SP;
31 use std::ops::ControlFlow;
33 /// Whether we do the orphan check relative to this crate or
34 /// to some remote crate.
35 #[derive(Copy, Clone, Debug)]
41 #[derive(Debug, Copy, Clone)]
47 pub struct OverlapResult<'tcx> {
48 pub impl_header: ty::ImplHeader<'tcx>,
49 pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause>,
51 /// `true` if the overlap might've been permitted before the shift
53 pub involves_placeholder: bool,
56 pub fn add_placeholder_note(err: &mut Diagnostic) {
58 "this behavior recently changed as a result of a bug fix; \
59 see rust-lang/rust#56105 for details",
63 /// If there are types that satisfy both impls, invokes `on_overlap`
64 /// with a suitably-freshened `ImplHeader` with those types
65 /// substituted. Otherwise, invokes `no_overlap`.
66 #[instrument(skip(tcx, skip_leak_check, on_overlap, no_overlap), level = "debug")]
67 pub fn overlapping_impls<F1, F2, R>(
71 skip_leak_check: SkipLeakCheck,
72 overlap_mode: OverlapMode,
77 F1: FnOnce(OverlapResult<'_>) -> R,
80 // Before doing expensive operations like entering an inference context, do
81 // a quick check via fast_reject to tell if the impl headers could possibly
83 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer };
84 let impl1_ref = tcx.impl_trait_ref(impl1_def_id);
85 let impl2_ref = tcx.impl_trait_ref(impl2_def_id);
86 let may_overlap = match (impl1_ref, impl2_ref) {
87 (Some(a), Some(b)) => iter::zip(a.substs, b.substs)
88 .all(|(arg1, arg2)| drcx.generic_args_may_unify(arg1, arg2)),
90 let self_ty1 = tcx.type_of(impl1_def_id);
91 let self_ty2 = tcx.type_of(impl2_def_id);
92 drcx.types_may_unify(self_ty1, self_ty2)
94 _ => bug!("unexpected impls: {impl1_def_id:?} {impl2_def_id:?}"),
98 // Some types involved are definitely different, so the impls couldn't possibly overlap.
99 debug!("overlapping_impls: fast_reject early-exit");
103 let infcx = tcx.infer_ctxt().build();
104 let selcx = &mut SelectionContext::intercrate(&infcx);
106 overlap(selcx, skip_leak_check, impl1_def_id, impl2_def_id, overlap_mode).is_some();
111 // In the case where we detect an error, run the check again, but
112 // this time tracking intercrate ambiguity causes for better
113 // diagnostics. (These take time and can lead to false errors.)
114 let infcx = tcx.infer_ctxt().build();
115 let selcx = &mut SelectionContext::intercrate(&infcx);
116 selcx.enable_tracking_intercrate_ambiguity_causes();
117 on_overlap(overlap(selcx, skip_leak_check, impl1_def_id, impl2_def_id, overlap_mode).unwrap())
120 fn with_fresh_ty_vars<'cx, 'tcx>(
121 selcx: &mut SelectionContext<'cx, 'tcx>,
122 param_env: ty::ParamEnv<'tcx>,
124 ) -> ty::ImplHeader<'tcx> {
125 let tcx = selcx.tcx();
126 let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
128 let header = ty::ImplHeader {
130 self_ty: tcx.bound_type_of(impl_def_id).subst(tcx, impl_substs),
131 trait_ref: tcx.bound_impl_trait_ref(impl_def_id).map(|i| i.subst(tcx, impl_substs)),
132 predicates: tcx.predicates_of(impl_def_id).instantiate(tcx, impl_substs).predicates,
135 let Normalized { value: mut header, obligations } =
136 traits::normalize(selcx, param_env, ObligationCause::dummy(), header);
138 header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
142 /// Can both impl `a` and impl `b` be satisfied by a common type (including
143 /// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
144 fn overlap<'cx, 'tcx>(
145 selcx: &mut SelectionContext<'cx, 'tcx>,
146 skip_leak_check: SkipLeakCheck,
149 overlap_mode: OverlapMode,
150 ) -> Option<OverlapResult<'tcx>> {
152 "overlap(impl1_def_id={:?}, impl2_def_id={:?}, overlap_mode={:?})",
153 impl1_def_id, impl2_def_id, overlap_mode
156 selcx.infcx().probe_maybe_skip_leak_check(skip_leak_check.is_yes(), |snapshot| {
157 overlap_within_probe(selcx, impl1_def_id, impl2_def_id, overlap_mode, snapshot)
161 fn overlap_within_probe<'cx, 'tcx>(
162 selcx: &mut SelectionContext<'cx, 'tcx>,
165 overlap_mode: OverlapMode,
166 snapshot: &CombinedSnapshot<'tcx>,
167 ) -> Option<OverlapResult<'tcx>> {
168 let infcx = selcx.infcx();
170 if overlap_mode.use_negative_impl() {
171 if negative_impl(selcx, impl1_def_id, impl2_def_id)
172 || negative_impl(selcx, impl2_def_id, impl1_def_id)
178 // For the purposes of this check, we don't bring any placeholder
179 // types into scope; instead, we replace the generic types with
180 // fresh type variables, and hence we do our evaluations in an
181 // empty environment.
182 let param_env = ty::ParamEnv::empty();
184 let impl1_header = with_fresh_ty_vars(selcx, param_env, impl1_def_id);
185 let impl2_header = with_fresh_ty_vars(selcx, param_env, impl2_def_id);
187 let obligations = equate_impl_headers(selcx, &impl1_header, &impl2_header)?;
188 debug!("overlap: unification check succeeded");
190 if overlap_mode.use_implicit_negative() {
191 if implicit_negative(selcx, param_env, &impl1_header, impl2_header, obligations) {
196 // We disable the leak when when creating the `snapshot` by using
197 // `infcx.probe_maybe_disable_leak_check`.
198 if infcx.leak_check(true, snapshot).is_err() {
199 debug!("overlap: leak check failed");
203 let intercrate_ambiguity_causes = selcx.take_intercrate_ambiguity_causes();
204 debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
206 let involves_placeholder =
207 matches!(selcx.infcx().region_constraints_added_in_snapshot(snapshot), Some(true));
209 let impl_header = selcx.infcx().resolve_vars_if_possible(impl1_header);
210 Some(OverlapResult { impl_header, intercrate_ambiguity_causes, involves_placeholder })
213 fn equate_impl_headers<'cx, 'tcx>(
214 selcx: &mut SelectionContext<'cx, 'tcx>,
215 impl1_header: &ty::ImplHeader<'tcx>,
216 impl2_header: &ty::ImplHeader<'tcx>,
217 ) -> Option<PredicateObligations<'tcx>> {
218 // Do `a` and `b` unify? If not, no overlap.
219 debug!("equate_impl_headers(impl1_header={:?}, impl2_header={:?}", impl1_header, impl2_header);
222 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
223 .eq_impl_headers(impl1_header, impl2_header)
224 .map(|infer_ok| infer_ok.obligations)
228 /// Given impl1 and impl2 check if both impls can be satisfied by a common type (including
229 /// where-clauses) If so, return false, otherwise return true, they are disjoint.
230 fn implicit_negative<'cx, 'tcx>(
231 selcx: &mut SelectionContext<'cx, 'tcx>,
232 param_env: ty::ParamEnv<'tcx>,
233 impl1_header: &ty::ImplHeader<'tcx>,
234 impl2_header: ty::ImplHeader<'tcx>,
235 obligations: PredicateObligations<'tcx>,
237 // There's no overlap if obligations are unsatisfiable or if the obligation negated is
240 // For example, given these two impl headers:
242 // `impl<'a> From<&'a str> for Box<dyn Error>`
243 // `impl<E> From<E> for Box<dyn Error> where E: Error`
247 // `Box<dyn Error>: From<&'?a str>`
248 // `Box<dyn Error>: From<?E>`
250 // After equating the two headers:
252 // `Box<dyn Error> = Box<dyn Error>`
253 // So, `?E = &'?a str` and then given the where clause `&'?a str: Error`.
255 // If the obligation `&'?a str: Error` holds, it means that there's overlap. If that doesn't
256 // hold we need to check if `&'?a str: !Error` holds, if doesn't hold there's overlap because
257 // at some point an impl for `&'?a str: Error` could be added.
259 "implicit_negative(impl1_header={:?}, impl2_header={:?}, obligations={:?})",
260 impl1_header, impl2_header, obligations
262 let infcx = selcx.infcx();
263 let opt_failing_obligation = impl1_header
267 .chain(impl2_header.predicates)
268 .map(|p| infcx.resolve_vars_if_possible(p))
269 .map(|p| Obligation {
270 cause: ObligationCause::dummy(),
276 .find(|o| !selcx.predicate_may_hold_fatal(o));
278 if let Some(failing_obligation) = opt_failing_obligation {
279 debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
286 /// Given impl1 and impl2 check if both impls are never satisfied by a common type (including
287 /// where-clauses) If so, return true, they are disjoint and false otherwise.
288 fn negative_impl<'cx, 'tcx>(
289 selcx: &mut SelectionContext<'cx, 'tcx>,
293 debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
294 let tcx = selcx.infcx().tcx;
296 // Create an infcx, taking the predicates of impl1 as assumptions:
297 let infcx = tcx.infer_ctxt().build();
298 // create a parameter environment corresponding to a (placeholder) instantiation of impl1
299 let impl_env = tcx.param_env(impl1_def_id);
300 let subject1 = match traits::fully_normalize(
302 ObligationCause::dummy(),
304 tcx.impl_subject(impl1_def_id),
308 tcx.sess.delay_span_bug(
309 tcx.def_span(impl1_def_id),
310 format!("failed to fully normalize {:?}: {:?}", impl1_def_id, err),
316 // Attempt to prove that impl2 applies, given all of the above.
317 let selcx = &mut SelectionContext::new(&infcx);
318 let impl2_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl2_def_id);
319 let (subject2, obligations) =
320 impl_subject_and_oblig(selcx, impl_env, impl2_def_id, impl2_substs);
322 !equate(&infcx, impl_env, subject1, subject2, obligations, impl1_def_id)
326 infcx: &InferCtxt<'tcx>,
327 impl_env: ty::ParamEnv<'tcx>,
328 subject1: ImplSubject<'tcx>,
329 subject2: ImplSubject<'tcx>,
330 obligations: impl Iterator<Item = PredicateObligation<'tcx>>,
333 // do the impls unify? If not, not disjoint.
334 let Ok(InferOk { obligations: more_obligations, .. }) =
335 infcx.at(&ObligationCause::dummy(), impl_env).eq(subject1, subject2)
337 debug!("explicit_disjoint: {:?} does not unify with {:?}", subject1, subject2);
341 let selcx = &mut SelectionContext::new(&infcx);
342 let opt_failing_obligation = obligations
344 .chain(more_obligations)
345 .find(|o| negative_impl_exists(selcx, o, body_def_id));
347 if let Some(failing_obligation) = opt_failing_obligation {
348 debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
355 /// Try to prove that a negative impl exist for the given obligation and its super predicates.
356 #[instrument(level = "debug", skip(selcx))]
357 fn negative_impl_exists<'cx, 'tcx>(
358 selcx: &SelectionContext<'cx, 'tcx>,
359 o: &PredicateObligation<'tcx>,
362 if resolve_negative_obligation(selcx.infcx().fork(), o, body_def_id) {
366 // Try to prove a negative obligation exists for super predicates
367 for o in util::elaborate_predicates(selcx.tcx(), iter::once(o.predicate)) {
368 if resolve_negative_obligation(selcx.infcx().fork(), &o, body_def_id) {
376 #[instrument(level = "debug", skip(infcx))]
377 fn resolve_negative_obligation<'tcx>(
378 infcx: InferCtxt<'tcx>,
379 o: &PredicateObligation<'tcx>,
384 let Some(o) = o.flip_polarity(tcx) else {
388 let param_env = o.param_env;
389 if !super::fully_solve_obligation(&infcx, o).is_empty() {
393 let (body_id, body_def_id) = if let Some(body_def_id) = body_def_id.as_local() {
394 (tcx.hir().local_def_id_to_hir_id(body_def_id), body_def_id)
396 (CRATE_HIR_ID, CRATE_DEF_ID)
399 let ocx = ObligationCtxt::new(&infcx);
400 let wf_tys = ocx.assumed_wf_types(param_env, DUMMY_SP, body_def_id);
401 let outlives_env = OutlivesEnvironment::with_bounds(
404 infcx.implied_bounds_tys(param_env, body_id, wf_tys),
407 infcx.process_registered_region_obligations(outlives_env.region_bound_pairs(), param_env);
409 infcx.resolve_regions(&outlives_env).is_empty()
412 pub fn trait_ref_is_knowable<'tcx>(
414 trait_ref: ty::TraitRef<'tcx>,
415 ) -> Result<(), Conflict> {
416 debug!("trait_ref_is_knowable(trait_ref={:?})", trait_ref);
417 if orphan_check_trait_ref(tcx, trait_ref, InCrate::Remote).is_ok() {
418 // A downstream or cousin crate is allowed to implement some
419 // substitution of this trait-ref.
420 return Err(Conflict::Downstream);
423 if trait_ref_is_local_or_fundamental(tcx, trait_ref) {
424 // This is a local or fundamental trait, so future-compatibility
425 // is no concern. We know that downstream/cousin crates are not
426 // allowed to implement a substitution of this trait ref, which
427 // means impls could only come from dependencies of this crate,
428 // which we already know about.
432 // This is a remote non-fundamental trait, so if another crate
433 // can be the "final owner" of a substitution of this trait-ref,
434 // they are allowed to implement it future-compatibly.
436 // However, if we are a final owner, then nobody else can be,
437 // and if we are an intermediate owner, then we don't care
438 // about future-compatibility, which means that we're OK if
440 if orphan_check_trait_ref(tcx, trait_ref, InCrate::Local).is_ok() {
441 debug!("trait_ref_is_knowable: orphan check passed");
444 debug!("trait_ref_is_knowable: nonlocal, nonfundamental, unowned");
445 Err(Conflict::Upstream)
449 pub fn trait_ref_is_local_or_fundamental<'tcx>(
451 trait_ref: ty::TraitRef<'tcx>,
453 trait_ref.def_id.krate == LOCAL_CRATE || tcx.has_attr(trait_ref.def_id, sym::fundamental)
456 pub enum OrphanCheckErr<'tcx> {
457 NonLocalInputType(Vec<(Ty<'tcx>, bool /* Is this the first input type? */)>),
458 UncoveredTy(Ty<'tcx>, Option<Ty<'tcx>>),
461 /// Checks the coherence orphan rules. `impl_def_id` should be the
462 /// `DefId` of a trait impl. To pass, either the trait must be local, or else
463 /// two conditions must be satisfied:
465 /// 1. All type parameters in `Self` must be "covered" by some local type constructor.
466 /// 2. Some local type must appear in `Self`.
467 pub fn orphan_check(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Result<(), OrphanCheckErr<'_>> {
468 debug!("orphan_check({:?})", impl_def_id);
470 // We only except this routine to be invoked on implementations
471 // of a trait, not inherent implementations.
472 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
473 debug!("orphan_check: trait_ref={:?}", trait_ref);
475 // If the *trait* is local to the crate, ok.
476 if trait_ref.def_id.is_local() {
477 debug!("trait {:?} is local to current crate", trait_ref.def_id);
481 orphan_check_trait_ref(tcx, trait_ref, InCrate::Local)
484 /// Checks whether a trait-ref is potentially implementable by a crate.
486 /// The current rule is that a trait-ref orphan checks in a crate C:
488 /// 1. Order the parameters in the trait-ref in subst order - Self first,
489 /// others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
490 /// 2. Of these type parameters, there is at least one type parameter
491 /// in which, walking the type as a tree, you can reach a type local
492 /// to C where all types in-between are fundamental types. Call the
493 /// first such parameter the "local key parameter".
494 /// - e.g., `Box<LocalType>` is OK, because you can visit LocalType
495 /// going through `Box`, which is fundamental.
496 /// - similarly, `FundamentalPair<Vec<()>, Box<LocalType>>` is OK for
498 /// - but (knowing that `Vec<T>` is non-fundamental, and assuming it's
499 /// not local), `Vec<LocalType>` is bad, because `Vec<->` is between
500 /// the local type and the type parameter.
501 /// 3. Before this local type, no generic type parameter of the impl must
502 /// be reachable through fundamental types.
503 /// - e.g. `impl<T> Trait<LocalType> for Vec<T>` is fine, as `Vec` is not fundamental.
504 /// - while `impl<T> Trait<LocalType> for Box<T>` results in an error, as `T` is
505 /// reachable through the fundamental type `Box`.
506 /// 4. Every type in the local key parameter not known in C, going
507 /// through the parameter's type tree, must appear only as a subtree of
508 /// a type local to C, with only fundamental types between the type
509 /// local to C and the local key parameter.
510 /// - e.g., `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
511 /// is bad, because the only local type with `T` as a subtree is
512 /// `LocalType<T>`, and `Vec<->` is between it and the type parameter.
513 /// - similarly, `FundamentalPair<LocalType<T>, T>` is bad, because
514 /// the second occurrence of `T` is not a subtree of *any* local type.
515 /// - however, `LocalType<Vec<T>>` is OK, because `T` is a subtree of
516 /// `LocalType<Vec<T>>`, which is local and has no types between it and
517 /// the type parameter.
519 /// The orphan rules actually serve several different purposes:
521 /// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where
522 /// every type local to one crate is unknown in the other) can't implement
523 /// the same trait-ref. This follows because it can be seen that no such
524 /// type can orphan-check in 2 such crates.
526 /// To check that a local impl follows the orphan rules, we check it in
527 /// InCrate::Local mode, using type parameters for the "generic" types.
529 /// 2. They ground negative reasoning for coherence. If a user wants to
530 /// write both a conditional blanket impl and a specific impl, we need to
531 /// make sure they do not overlap. For example, if we write
532 /// ```ignore (illustrative)
533 /// impl<T> IntoIterator for Vec<T>
534 /// impl<T: Iterator> IntoIterator for T
536 /// We need to be able to prove that `Vec<$0>: !Iterator` for every type $0.
537 /// We can observe that this holds in the current crate, but we need to make
538 /// sure this will also hold in all unknown crates (both "independent" crates,
539 /// which we need for link-safety, and also child crates, because we don't want
540 /// child crates to get error for impl conflicts in a *dependency*).
542 /// For that, we only allow negative reasoning if, for every assignment to the
543 /// inference variables, every unknown crate would get an orphan error if they
544 /// try to implement this trait-ref. To check for this, we use InCrate::Remote
545 /// mode. That is sound because we already know all the impls from known crates.
547 /// 3. For non-`#[fundamental]` traits, they guarantee that parent crates can
548 /// add "non-blanket" impls without breaking negative reasoning in dependent
549 /// crates. This is the "rebalancing coherence" (RFC 1023) restriction.
551 /// For that, we only a allow crate to perform negative reasoning on
552 /// non-local-non-`#[fundamental]` only if there's a local key parameter as per (2).
554 /// Because we never perform negative reasoning generically (coherence does
555 /// not involve type parameters), this can be interpreted as doing the full
556 /// orphan check (using InCrate::Local mode), substituting non-local known
557 /// types for all inference variables.
559 /// This allows for crates to future-compatibly add impls as long as they
560 /// can't apply to types with a key parameter in a child crate - applying
561 /// the rules, this basically means that every type parameter in the impl
562 /// must appear behind a non-fundamental type (because this is not a
563 /// type-system requirement, crate owners might also go for "semantic
564 /// future-compatibility" involving things such as sealed traits, but
565 /// the above requirement is sufficient, and is necessary in "open world"
568 /// Note that this function is never called for types that have both type
569 /// parameters and inference variables.
570 fn orphan_check_trait_ref<'tcx>(
572 trait_ref: ty::TraitRef<'tcx>,
574 ) -> Result<(), OrphanCheckErr<'tcx>> {
575 debug!("orphan_check_trait_ref(trait_ref={:?}, in_crate={:?})", trait_ref, in_crate);
577 if trait_ref.needs_infer() && trait_ref.needs_subst() {
579 "can't orphan check a trait ref with both params and inference variables {:?}",
584 let mut checker = OrphanChecker::new(tcx, in_crate);
585 match trait_ref.visit_with(&mut checker) {
586 ControlFlow::Continue(()) => Err(OrphanCheckErr::NonLocalInputType(checker.non_local_tys)),
587 ControlFlow::Break(OrphanCheckEarlyExit::ParamTy(ty)) => {
588 // Does there exist some local type after the `ParamTy`.
589 checker.search_first_local_ty = true;
590 if let Some(OrphanCheckEarlyExit::LocalTy(local_ty)) =
591 trait_ref.visit_with(&mut checker).break_value()
593 Err(OrphanCheckErr::UncoveredTy(ty, Some(local_ty)))
595 Err(OrphanCheckErr::UncoveredTy(ty, None))
598 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(_)) => Ok(()),
602 struct OrphanChecker<'tcx> {
606 /// Ignore orphan check failures and exclusively search for the first
608 search_first_local_ty: bool,
609 non_local_tys: Vec<(Ty<'tcx>, bool)>,
612 impl<'tcx> OrphanChecker<'tcx> {
613 fn new(tcx: TyCtxt<'tcx>, in_crate: InCrate) -> Self {
618 search_first_local_ty: false,
619 non_local_tys: Vec::new(),
623 fn found_non_local_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx>> {
624 self.non_local_tys.push((t, self.in_self_ty));
625 ControlFlow::CONTINUE
628 fn found_param_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx>> {
629 if self.search_first_local_ty {
630 ControlFlow::CONTINUE
632 ControlFlow::Break(OrphanCheckEarlyExit::ParamTy(t))
636 fn def_id_is_local(&mut self, def_id: DefId) -> bool {
637 match self.in_crate {
638 InCrate::Local => def_id.is_local(),
639 InCrate::Remote => false,
644 enum OrphanCheckEarlyExit<'tcx> {
649 impl<'tcx> TypeVisitor<'tcx> for OrphanChecker<'tcx> {
650 type BreakTy = OrphanCheckEarlyExit<'tcx>;
651 fn visit_region(&mut self, _r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
652 ControlFlow::CONTINUE
655 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
656 let result = match *ty.kind() {
670 | ty::Projection(..) => self.found_non_local_ty(ty),
672 ty::Param(..) => self.found_param_ty(ty),
674 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => match self.in_crate {
675 InCrate::Local => self.found_non_local_ty(ty),
676 // The inference variable might be unified with a local
677 // type in that remote crate.
678 InCrate::Remote => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
681 // For fundamental types, we just look inside of them.
682 ty::Ref(_, ty, _) => ty.visit_with(self),
683 ty::Adt(def, substs) => {
684 if self.def_id_is_local(def.did()) {
685 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
686 } else if def.is_fundamental() {
687 substs.visit_with(self)
689 self.found_non_local_ty(ty)
692 ty::Foreign(def_id) => {
693 if self.def_id_is_local(def_id) {
694 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
696 self.found_non_local_ty(ty)
699 ty::Dynamic(tt, ..) => {
700 let principal = tt.principal().map(|p| p.def_id());
701 if principal.map_or(false, |p| self.def_id_is_local(p)) {
702 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
704 self.found_non_local_ty(ty)
707 ty::Error(_) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
708 ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(..) => {
709 self.tcx.sess.delay_span_bug(
711 format!("ty_is_local invoked on closure or generator: {:?}", ty),
713 ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
716 // This merits some explanation.
717 // Normally, opaque types are not involved when performing
718 // coherence checking, since it is illegal to directly
719 // implement a trait on an opaque type. However, we might
720 // end up looking at an opaque type during coherence checking
721 // if an opaque type gets used within another type (e.g. as
722 // the type of a field) when checking for auto trait or `Sized`
723 // impls. This requires us to decide whether or not an opaque
724 // type should be considered 'local' or not.
726 // We choose to treat all opaque types as non-local, even
727 // those that appear within the same crate. This seems
728 // somewhat surprising at first, but makes sense when
729 // you consider that opaque types are supposed to hide
730 // the underlying type *within the same crate*. When an
731 // opaque type is used from outside the module
732 // where it is declared, it should be impossible to observe
733 // anything about it other than the traits that it implements.
735 // The alternative would be to look at the underlying type
736 // to determine whether or not the opaque type itself should
737 // be considered local. However, this could make it a breaking change
738 // to switch the underlying ('defining') type from a local type
739 // to a remote type. This would violate the rule that opaque
740 // types should be completely opaque apart from the traits
741 // that they implement, so we don't use this behavior.
742 self.found_non_local_ty(ty)
745 // A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so
746 // the first type we visit is always the self type.
747 self.in_self_ty = false;
751 /// All possible values for a constant parameter already exist
752 /// in the crate defining the trait, so they are always non-local[^1].
754 /// Because there's no way to have an impl where the first local
755 /// generic argument is a constant, we also don't have to fail
756 /// the orphan check when encountering a parameter or a generic constant.
758 /// This means that we can completely ignore constants during the orphan check.
760 /// See `src/test/ui/coherence/const-generics-orphan-check-ok.rs` for examples.
762 /// [^1]: This might not hold for function pointers or trait objects in the future.
763 /// As these should be quite rare as const arguments and especially rare as impl
764 /// parameters, allowing uncovered const parameters in impls seems more useful
765 /// than allowing `impl<T> Trait<local_fn_ptr, T> for i32` to compile.
766 fn visit_const(&mut self, _c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
767 ControlFlow::CONTINUE