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